Assignments within sub-expressions are hard to spot and therefore make the code less readable. Ideally, sub-expressions should not have
side-effects.
Moreover, using chained assignment in declarations is also dangerous because one may accidentally create global variables, e.g. in let x = y
= 1;
, if y
is not declared, it will be hoisted as global.
Noncompliant Code Example
if (val = value() && check()) { // Noncompliant
// ...
}
Compliant Solution
val = value();
if (val && check()) {
// ...
}
Exceptions
The rule does not raise issues for the following patterns:
- chained assignments:
a = b = c = 0;
- relational assignments:
(a = 0) != b
- sequential assignments:
a = 0, b = 1, c = 2
- assignments in lambda body:
() => a = 0
- conditional assignment idiom:
a || (a = 0)
- assignments in (do-)while conditions:
while (a = 0);
See