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++) { // Noncompliant: both loops use same variable
}
for (var i = 0; i < n; i++) {
}
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) {
var x;
if (a > b) {
x = a - b;
}
if (a > 4) {
console.log(x);
}
for (let i = 0; i < m; i++) {
}
for (let i = 0; i < n; i++) {
}
return a + b;
}