JavaScript variable scope can be particularly difficult to understand and get right. The situation gets even worse when you consider the
accidental creation of global variables, which is what happens when you declare a variable inside a function or the for
clause
of a for-loop without using the let
, const
or var
keywords.
let
and const
were introduced in ECMAScript 2015, and are now the preferred keywords for variable declaration.
Noncompliant Code Example
function f(){
i = 1; // Noncompliant; i is global
for (j = 0; j < array.length; j++) { // Noncompliant; j is global now too
// ...
}
}
Compliant Solution
function f(){
var i = 1;
for (let j = 0; j < array.length; j++) {
// ...
}
}