Assignment to constant¶
ID: js/assignment-to-constantKind: problemSecurity severity: Severity: errorPrecision: very-highTags: - quality - reliability - correctnessQuery suites: - javascript-security-and-quality.qls
Click to see the query in the CodeQL repository
Most popular JavaScript platforms supportconst declarations, although this feature is not part of the ECMAScript 5 standard. Assigning a new value to a variable that is declaredconst does not result in an error on current platforms, and simply has no effect. Relying on this behavior is error-prone, particularly since ECMAScript 2015 prohibits such assignments.
Recommendation¶
If the variable genuinely needs to be reassigned, change its declaration fromconst tovar, or merge the assignment into the variable declaration, if possible. Otherwise, remove the spurious assignment.
Example¶
In the following example,loc is initialized tonull, and then set to either"here" or"there", depending on the value of variabledist. Most current platforms, however, will ignore the assignments entirely, soloc will retain its original valuenull.
constloc=null;if(dist<10)loc="here";elseloc="there";
Instead, the assignments toloc can be merged into its declaration like this:
constloc=dist<10?"here":"there";
References¶
Mozilla Developer Network:const.