The var statement declares variables that are function-scoped or globally-scoped. var declarations are hoisted, meaning
declaring a variable anywhere in the code is equivalent to declaring it at the top of the function or the script.
Even if hoisted, it is still recommended to declare the variable inside the block it is used. This improves readability and maintainability because it makes it clear where the variable is being used. The code then becomes easier to understand and follow, especially for other developers who may be working on the same codebase.
function doSomething(a, b) {
if (a > b) {
var x = a - b; // Noncompliant: 'x' is used later outside this block
}
if (a > 4) {
console.log(x);
}
for (var i = 0; i < m; i++) {
}
console.log(i); // Noncompliant: 'i' is referenced after the loop
return a + b;
}
When var declaration is used outside of a block, the declaration should be done at the uppermost level where it is used. When
possible, use let or const, which allow for block-scoped variables.
function doSomething(a, b) {
let x;
if (a > b) {
x = a - b;
}
if (a > 4) {
console.log(x);
}
let i;
for (i = 0; i < m; i++) {
}
console.log(i);
return a + b;
}
Reusing a var counter across sequential for loops is also compliant. Since var is hoisted to function scope,
each loop re-declares the same variable, and references that stay inside each loop do not appear outside the loop body.
function processItems(items, extras) {
for (var n in items) {
process(n);
}
for (var n = extras.length - 1; n >= 0; n--) {
extras[n].remove();
}
console.log(n); // Noncompliant: 'n' is referenced after all loops
}
function processItems(items, extras) {
for (var n in items) {
process(n);
}
for (var n = extras.length - 1; n >= 0; n--) {
extras[n].remove();
}
}