Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does 'let' override a global declaration and throws a ReferenceError?

I was going through the Difference between var and let documentation example and was testing that when an undeclared variable is invoked, the global scope automatically provides a declaration for it (that's why the following snippet does not throw an error in any of the variables):

x = 3;
console.log(x);

(function() {
  y=x+39;
})()
console.log(y);

However, when one variable is declared with let after the assignment in the same global scope:

x=3;
let x = 42;
console.log(x);

One of the following errors is thrown:

ReferenceError: x is not defined (Chromium)

ReferenceError: can't access lexical declaration x before initialization (Firefox)

I understand that let does not allow x to hoist, but since it was previously referenced (implying an automatic declaration from the global scope) shouldn't in this case a re-declaration happen?

SyntaxError: Identifierx has already been declared

And therefore the error above thrown?

I also understand that in strict mode the first snippet would throw a ReferenceError, so does this mean that let forces this particular rule of strict mode (all variables need to be declared) upon the global scope?

like image 826
CPHPython Avatar asked Jan 03 '17 19:01

CPHPython


1 Answers

Did you have a look at the let docs at MDN? They describe a temporal dead zone and errors with let.

ES6 does hoist a let variable to the top of its scope. Differently to var variable, when using let you must not access the variable before it is declared. Doing so fail with a ReferenceError (a.k.a. let's temporal dead zone).

like image 102
Konstantin A. Magg Avatar answered Sep 20 '22 10:09

Konstantin A. Magg