Require or disallow Yoda Conditions (yoda)

The --fix option on the command line can automatically fix some of the problems reported by this rule.

Yoda conditions are so named because the literal value of the condition comes first while the variable comes second. For example, the following is a Yoda condition:

if("red"===color){// ...}

This is called a Yoda condition because it reads as, “if red equals the color”, similar to the way the Star Wars character Yoda speaks. Compare to the other way of arranging the operands:

if(color==="red"){// ...}

This typically reads, “if the color equals red”, which is arguably a more natural way to describe the comparison.

Proponents of Yoda conditions highlight that it is impossible to mistakenly use = instead of == because you cannot assign to a literal value. Doing so will cause a syntax error and you will be informed of the mistake early on. This practice was therefore very common in early programming where tools were not yet available.

Opponents of Yoda conditions point out that tooling has made us better programmers because tools will catch the mistaken use of = instead of == (ESLint will catch this for you). Therefore, they argue, the utility of the pattern doesn’t outweigh the readability hit the code takes while using Yoda conditions.

Rule Details

This rule aims to enforce consistent style of conditions which compare a variable to a literal value.

Options

This rule can take a string option:

If it is the default "never", then comparisons must never be Yoda conditions.

If it is "always", then the literal value must always come first.

The default "never" option can have exception options in an object literal:

If the "exceptRange" property is true, the rule allows yoda conditions in range comparisons which are wrapped directly in parentheses, including the parentheses of an if or while condition. The default value is false. A range comparison tests whether a variable is inside or outside the range between two literal values.

If the "onlyEquality" property is true, the rule reports yoda conditions only for the equality operators == and ===. The default value is false.

The onlyEquality option allows a superset of the exceptions which exceptRange allows, thus both options are not useful together.