Assignment in Condition
ID |
javascript.assign_in_condition |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
CWE:481, reliability, suspicious-comparison |
Description
Reports an assignment used as the condition of an if, while, do-while, or ternary (?:). Almost always a typo for == / === — the assignment evaluates to the assigned value, not a comparison.
If the assignment is genuinely intentional, wrap it in an extra set of parentheses (if x = next()) — that documents the intent and the rule will not fire.
Rationale
-
if (x = 5)does not comparexagainst 5; it assigns 5 toxand the branch fires because 5 is truthy. -
while (next = step())is a recognised idiom (loop untilstep()returns a falsy value), but only when the parens make the assignment explicit. Without them the reader can’t tell the assignment from a typo. -
The bug is invisible in tests because tests usually drive the assignment to a truthy value.
// Bad
if (x = 5) { ... }
while (next = step()) { ... }
return (x = 1) ? "a" : "b";