yoda
UnreleasedConfiguration
Rule Details
Yoda conditions are so named because the literal value of the condition comes first while the variable comes second, e.g. if ("red" === color). This rule enforces a consistent style of conditions which compare a variable to a literal value.
Examples of incorrect code for this rule, with the default "never" option:
Examples of correct code for this rule, with the default "never" option:
Options
This rule takes a string option:
"never"(default): comparisons must never be Yoda conditions."always": the literal value must always come first.
The "never" option can take exception options in an object literal:
exceptRange: whentrue, allows Yoda conditions in range comparisons that are wrapped directly in parentheses, including the parentheses of aniforwhilecondition. A range comparison tests whether a variable is inside or outside the range between two literal values. Defaultfalse.onlyEquality: whentrue, only reports Yoda conditions for the equality operators==and===. Defaultfalse.
onlyEquality allows a superset of the exceptions exceptRange allows, so combining both options together isn't useful.
Examples of correct code for this rule with { "exceptRange": true }:
Each parenthesized pair of comparisons forms one range comparison, so a range comparison combined with a further condition needs its own parentheses.
Examples of correct code for this rule with { "onlyEquality": true }:
Examples of incorrect code for this rule with the "always" option:
Examples of correct code for this rule with the "always" option:
Differences from ESLint
- TypeScript-only wrappers with no runtime effect —
x!,x as T,x satisfies T— are read through when deciding whether the two comparisons of a range test hold the same operand. With{ "exceptRange": true },if (0 <= x! && x! < 1) {}reads as one range comparison and stays exempt.