Variables should not be shadowed

Why you should care

Overriding a variable declared in an outer scope can strongly impact the readability, and therefore the maintainability, of a piece of code. Further, it could lead maintainers to introduce bugs because they think they’re using one variable but are really using another.

How we detect

CAST Highlight counts one occurrence each time a variable declaration (with var, let or const) is hidding another upper level declaration (variable or parameter).

function foo() {
if (x > 0) {
let y = bar(2); // no shadowing
} else {
let y = bar(3); // no shadowing
}
}
function foo() {
if (x > 0) {
let y = bar(2); // the let declaration is shadowing the var declaration.
} else {
var y = bar(3);
}
}
function foo() {
let y = bar(2); // do not compile because "let y" and "var y" are both in the full function scope.
if (x > 0) {
var y = bar(3);
}
}
function foo() {
if (x > 0) {
let y = 0; // y is not conflicting with "var y" because "var y" is in the full scope of the function, while "let y" is in the scope of the "if" statement". So "let y" is shadowing "var y".
while (more) {
var y = bar(3);
}
}
}

References

5362

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.