var Redeclaration
ID |
javascript.variable_redeclaration |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
JavaScript |
Tags |
code-style, scope |
Description
Reports the second and subsequent var declarations of the same name within the same function scope (or the module scope, for top-level `var`s). JavaScript silently merges them into a single binding; the second declaration reads as "this is a fresh variable" but in fact retains whatever value the first one had at that point.
let and const are not flagged because the parser / runtime already rejects duplicate declarations as SyntaxError.
Rationale
// Bad — silent merge into one binding.
function bad() {
var counter = 0;
var counter = counter + 1;
return counter;
}
var hoists to the function scope, so even nested-block redeclarations affect the same binding:
// Bad — block re-declares the function-scoped `var`.
function badBlock() {
var name = "first";
if (true) {
var name = "second";
}
return name;
}
Remediation
Pick one of:
-
Drop the second
var— keep only the first declaration and the subsequent assignment. -
Switch the binding kind to
let(block-scoped, so a nested block can have its own). -
Rename the second variable when the two are conceptually different.