Self-Assignment
ID |
javascript.self_assignment |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
CWE:480, reliability, suspicious-comparison |
Description
Reports an assignment whose two sides are the same expression: x = x, this.count = this.count, a[i] = a[i]. The statement has no effect at run time.
The two sides are compared over the parsed tokens, so comments, whitespace and line breaks are ignored while a difference in operand, property or index is not. Compound assignments are a different statement and are never reported — x += x doubles x. Either side is also left alone when it contains a call or an increment, since those make two textually identical sides evaluate differently.
Rationale
// Bad
function Counter(count) {
this.count = this.count; // meant: this.count = count
}
function copy(src, dst, i) {
dst[i] = dst[i]; // meant: dst[i] = src[i]
}
-
The statement is either dead weight or, far more often, a typo for the assignment that was meant — a missing
this.on one side, or an operand left unchanged after a copy-paste. -
Nothing fails: the field keeps its previous value (frequently
undefined) and the defect surfaces much later, far from its cause. -
A self-assignment used deliberately as a "mark this parameter as used" trick has no effect either; a lint suppression or an explicit
void xsays so plainly.