yoda
Require or disallow comparisons with the literal on the left
A "Yoda condition" puts the literal first: "red" === color instead of color === "red". Most people read the second form more easily, because it matches how you say it: "if the color is red".
The rule checks ==, ===, !=, !==, <, >, <= and >= where exactly one side is a literal. Negative numbers and template literals without ${} count as literals.
--fix swaps the two sides and flips the operator where needed, so 0 < count becomes count > 0.
Configure#
Off by default. To turn it on:
[lint.rules]
"yoda" = "error" # or "warn"Every option, set to its default:
[lint.rules]
"yoda" = [
"error",
"never", # "always" or "never"
{
exceptRange = false,
onlyEquality = false,
},
]Examples#
if ("red" === colorExpected literal to be on the right side of ===.) {
stop();
}
if (0 < countExpected literal to be on the right side of <.) {
render();
}if (color === "red") {
stop();
}
if (count > 0) {
render();
}Options#
[lint.rules]
yoda = ["error", "never", { exceptRange = true }]The first option is "never" (default), which wants the literal on the right, or "always", which wants it on the left. The second is an object:
| Option | Default | What it does |
|---|---|---|
exceptRange | false | Allow a range test in parentheses, such as (0 <= x && x < 10). |
onlyEquality | false | Only check == and ===. |
With exceptRange, the value can sit between its two limits, or outside them:
"never", { "exceptRange": true }No problemsif (0 <= index && index < items.length) {
select(index);
}
if (value < 0 || 100 < value) {
reject(value);
}The parentheses of an if, a while or a call count. Without any around the test, it's still reported:
"never", { "exceptRange": true }1 problemconst isPercent = 0 <= valueExpected literal to be on the right side of <=. && value <= 100;With onlyEquality, this isn't reported:
"never", { "onlyEquality": true }No problemsif (0 < count) {
render();
}