No const Reassignment
ID |
javascript.no_const_assign |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
reliability, suspicious-assignment |
Description
Reports any reassignment of a const-declared binding. Both plain x = … / compound x += … assignments and increment / decrement operators (x++, --x) qualify. Property assignments on a const object — obj.foo = … — are not reported; const constrains the binding, not the value.
Rationale
-
In strict mode the assignment throws a
TypeErrorat runtime — a hard crash where the originalconstdeclaration is correct. -
In sloppy mode (still common in script files, imported scripts, and many bundlers) the assignment is silently ignored, so
xkeeps its original value while the author thinks it was updated. That is the worst kind of bug — invisible. -
TypeScript catches this at compile time, but plain JavaScript does not. A static check before the change reaches CI saves a class of late-stage failures.
// Bad
const max = 100;
max = 200; // TypeError under strict mode, silent no-op otherwise
const i = 0;
i++; // same TypeError
Remediation
If the binding really should change, declare it with let. If the assignment was a typo, rename the new binding so the existing const is left intact.
// Good
let max = 100;
max = 200;
// Or — keep the const and use a separate binding for the new value
const max = 100;
let scaled = max * 2;