This is caused by hoisting the internal let
or const
to the top of the block (MDN), and create a Temporal Dead Zone.
In ECMAScript 2015, let will hoist the variable to the top of the
block. However, referencing the variable in the block before the
variable declaration results in a ReferenceError. The variable is in a
"temporal dead zone" from the start of the block until the declaration
is processed.
The reason behind this is simple - silent failing vs throwing error.
In this example, a similar setting is giving the result as undefined
because of the var
hoisting. This is a silent error, and it might be very hard to debug.
{
var a = 'a1';
(function() {
console.log(a);
var a = 'a2';
})();
}
If you'll use let
or const
an error will be thrown:
{
let a = 'a1';
(function() {
console.log(a);
let a = 'a2';
})();
}
You can find more info about the temporal dead zone in the article TEMPORAL DEAD ZONE (TDZ) DEMYSTIFIED.