Variable shadowing happens when a variable declared in a specific scope has the same name as a variable in an outer scope.
This can lead to three main problems:
- Confusion: The same name can refer to different variables in different parts of the scope, making the code hard to read and understand.
- Unintended Behavior: You might accidentally use the wrong variable, leading to hard-to-detect bugs.
- Maintenance Issues: If the inner variable is removed or renamed, the code’s behavior might change unexpectedly because the outer variable is
now being used.
To avoid these problems, rename the shadowing, shadowed, or both variables to accurately represent their purpose with unique and meaningful
names.
Note that functions in JavaScript are first-class citizens. This means that they possess the same attributes as variables, including the ability to
shadow other variables and, conversely, be shadowed by them.
Noncompliant code example
The example below shows the typical situations in which shadowing can occur.
function outer(items) {
var counter = 0;
function inner(items) { // Noncompliant: the parameter "items" is shadowed.
var counter = counter + 1; // Noncompliant: the outer "counter" is shadowed.
}
inner(items);
return counter; // returns 0
}
function search(items, match) { // Noncompliant: the function "match" (below) is shadowed.
// ...
}
function match(value, key) {
// ...
}