Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of let hoisting in ES6?

I understand that let will be hoisted to top of the block, but accessing it before initializing will throw ReferenceErrordue being in to Temporal Dead Zone

For example:

console.log(x);   // Will throw Reference Error
let x = 'some value';

But a snippet like this will run without error:

foo(); // alerts foo;
function foo(){    // foo will be hoisted 
  alert("foo");
} 

My question

What is purpose of let getting hoisted to top when it will throw an error on accessing? Also do var also suffer from TDZ,I know when it will throw undefined but is it because of TDZ?

like image 844
brk Avatar asked Feb 24 '16 09:02

brk


2 Answers

The documentation says:

The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated. A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created. If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.

Also the var keyword :

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

You can also check this article by Kyle Simpson: For and against let

like image 107
Rahul Tripathi Avatar answered Sep 21 '22 23:09

Rahul Tripathi


http://www.2ality.com/2015/10/why-tdz.html explains it in a nice way and also links to https://mail.mozilla.org/pipermail/es-discuss/2012-September/024996.html which is a related discussion on the topic.

Paraphrasing the content for this question

Why is there a temporal dead zone for let?

  1. If the TDZ did not cause a reference error, and you accessed a variable before its declaration (i.e. in the TDZ) you'd (most probably) be missing a programming mistake. The TDZ causing the reference error helps you catch your programming mistake.

  2. So your next question would be - why even have a TDZ for let? Why not start the scope of a let variable when its declared? The answer is const. TDZs are for const and (poor) let got stuck with TDZ just to make it easier to switch between let and const


Also do var also suffer from TDZ, I know when it will throw undefined but is it because of TDZ?

No, var does not suffer from TDZ. It does not throw any error. It is simply undefined till set otherwise. TDZ is an ES6 thing.

like image 23
potatopeelings Avatar answered Sep 21 '22 23:09

potatopeelings