How does JavaScript Hoisting really work?

w3schools js reference simply states that

Hoisting is JavaScript's default behavior of moving declarations to the top (of the scope)

Note that var a = 2; is actually declaration and assignment both! just the declaration part is moved to top of the scope!). However, as we will see later in this article this explanation is just some metaphorical description of the behavior of the js engine, in reality there is no moving!

I assume that you are familiar with the meaning of scope(if not, check out this first).

In JavaScript scope is lexical, meaning that it is fully specified at author time by the developer.

The key point to understand hoisting is that engine finds out about scopes in the code, during the compilation time NOT in execution time! So while the code is being compiled, engine creates and maintains scope. this created information is used as the code gets executed.

See the code below:

console.log(a);  // does NOT throw ReferenceError as you might thought
var a = 2;

The first line of the code above does not throw ReferenceError. That's because engine got to know about a much sooner during the compilation phase.

So the term hoisting technically is referring to the fact that declarations are handled before execution time during compilation. Here we reach a question: aren't declarations made using let and const keywords (added in ES6) handled during compilation too?(Yes, they are!) So, why does w3schools claim that declarations made by let and const are not hoisted?why does the code below result in ReferenceError?

console.log(b);
let b = 3;

To answer this question, some people come with such explanations:

In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the variable in the block before the variable declaration results in a ReferenceError because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

To be honest, that does not make sense to me. I can't understand how does initialization even matter when we are talking about ReferenceError!

The quoted text, is introducing a new term : temporal dead zone . By that, it is referring to the gap between start of the scope and the line of code where the variable is being declared! it is recommended to minimize TDZs as much as possible, cause they slow down the program.

#cs_internship #web

要查看或添加评论,请登录

Shahryar Saljoughi的更多文章

社区洞察

其他会员也浏览了