Don't Use Yoda Conditions in Frontend
In frontend code, I was never settled on whether to put the constant on the left or the variable on the left in conditionals. Without a decision there’s no standard, and without a standard both styles coexist in the codebase, which feels messy. While searching around, I stumbled on the term
Yoda conditions
—that seemed to hold the answer, hence this post.
Yoda conditions?
Yoda conditions are a programming style where the two sides of an expression in a conditional appear in the reverse of the typical order. The name comes from Jedi Master Yoda in Star Wars, who speaks with inverted word order. For example: “When nine hundred years old you reach, look as good you will not.”
Examples
if ( $value == 42 ) { /* ... */ }
// Reads like: "If the value is equal to 42..."
// 尤达表达式
if ( 42 == $value ) { /* ... */ }
// Reads like: "If 42 equals the value..."
Now it’s clear—this is what “Yoda conditions” refers to.
Pros and cons of Yoda conditions
Pros
Accidental assignment gets caught
For example, if we mistakenly write
=
instead of===
in a conditional,value = 1
won’t throw, but1 = value
will fail immediately, making the mistake obvious.Addresses unsafe null comparisons in Java
Cons
- Hurts readability
Conclusion
Regarding the first “pro,” even if putting the variable first can hide the mistake, such errors can and should be prevented by other means—lint rules or even code review. The second “pro” applies in languages like Java; in JavaScript, whether the variable is on the left or right doesn’t actually prevent null-related issues. The downside is clear.
Overall, the drawbacks of Yoda conditions outweigh the benefits. My recommendation: don’t use Yoda conditions in frontend code.
Lint
Having reached a conclusion, we should enforce the preferred style. We typically add a linter to control code style, and Yoda-style comparisons have corresponding rules we can enable to control conditional expressions.
In ESLint
"yoda":"never"
See docs: link
In TSLint
"binary-expression-operand-order": true
See docs: link
Final Thoughts
- It might seem that as long as a conditional works, the exact form doesn’t matter. No—details like Yoda conditions reflect thoughtful consideration of coding style by good engineers, and we should think about them too.
- It was precisely this pursuit of better conditional style that led me to learn about Yoda conditions. So, “sweating the details is never overkill.”