This question already has an answer here:
- Are variables declared with let or const not hoisted in ES6? 3 answers
The following code throws a ReferenceError 'a is not defined'.
{
let a = 'a1';
{
console.log(a);
let a = 'a2';
}
}
As do the next one.
{
const a = 'a1';
{
console.log(a);
const a = 'a2';
}
}
If you instead use var declarations it works as I expect it to. (No error error thrown and 'a1' logged.)
It gets even harder for me to comprehend when I try to analyze the following code.
{
let a = 'a1';
{
console.log(a);
var a = 'a2';
}
}
It throws a SyntaxError, "Identifier 'a' has already been declared".
Naïvely I expected an identifier to be shadowed not until after a let or const declaration, like the behavior of let in Clojure or let* in Racket. As described clearly on MDN, this is not how it works.
But why does it work this way? Why does Racket have both a let and a let* form?