Java Reference
In-Depth Information
}());
console.log(a);
<< 2
console.log(b);
<< 1
console.log(temp);
<< Error: "temp is not defined"
Mimicking Block Scope
In most other languages, a variable has scope inside a code block―that's what's known as
block scope . But this does not happen in JavaScript; variables only have a limited scope
inside functions. This means that when a temporary variable is created inside an if block
or a for loop, the variable will still be available outside of that block:
var list = [1,2,3];
for (var i = 0, max = list.length ; i < max ; i++ ){
console.log(list[i]);
}
console.log(i); // i is still available outside the for
block
<< 1
<< 2
<< 3
<< 3
The solution to this is to place the for block inside an IIFE to mimic block scope:
var list = [1,2,3];
(function(){for (var i = 0, max = list.length ; i < max ;
i++ ){
console.log(list[i]);
}}());
console.log(i); // i is not available outside the for block
Search WWH ::




Custom Search