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 compare x against 5; it assigns 5 to x and the branch fires because 5 is truthy.

  • while (next = step()) is a recognised idiom (loop until step() 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";

Remediation

Replace the assignment with the intended comparison, or wrap the assignment in explicit parentheses to document the intent.

// Good
if (x === 5) { ... }
while ((next = step())) { ... }