Variable Not Hoisting
let
will not hoist to the entire scope of the block they appear in. By contrast, var
could hoist as below.
{
console.log(cc); // undefined. Caused by hoisting
var cc = 23;
}
{
console.log(bb); // ReferenceError: bb is not defined
let bb = 23;
}
Actually, Per @Bergi, Both var
and let
are hoisted.
Garbage Collection
Block scope of let
is useful relates to closures and garbage collection to reclaim memory. Consider,
function process(data) {
//...
}
var hugeData = { .. };
process(hugeData);
var btn = document.getElementById("mybutton");
btn.addEventListener( "click", function click(evt){
//....
});
The click
handler callback does not need the hugeData
variable at all. Theoretically, after process(..)
runs, the huge data structure hugeData
could be garbage collected. However, it's possible that some JS engine will still have to keep this huge structure, since the click
function has a closure over the entire scope.
However, the block scope can make this huge data structure to garbage collected.
function process(data) {
//...
}
{ // anything declared inside this block can be garbage collected
let hugeData = { .. };
process(hugeData);
}
var btn = document.getElementById("mybutton");
btn.addEventListener( "click", function click(evt){
//....
});
let
loops
let
in the loop can re-binds it to each iteration of the loop, making sure to re-assign it the value from the end of the previous loop iteration. Consider,
// print '5' 5 times
for (var i = 0; i < 5; ++i) {
setTimeout(function () {
console.log(i);
}, 1000);
}
However, replace var
with let
// print 1, 2, 3, 4, 5. now
for (let i = 0; i < 5; ++i) {
setTimeout(function () {
console.log(i);
}, 1000);
}
Because let
create a new lexical environment with those names for a) the initialiser expression b) each iteration (previosly to evaluating the increment expression), more details are here.