Understand hoisting in Javascript

Yoni Weisbrod
InstructorYoni Weisbrod
Share this video with your friends

Social Share Links

Send Tweet

This lesson delves into the different ways in which variables and functions are hoisted in Javascript. Note that everything is hoisted but they're not all hoisted in the same way.

Function declarations are completely hoisted, so that you can always reference a function declaration before it's defined.

Variables declared with var are also hoisted, and their values are initialized to undefined. let and const, on the other hand, are hoisted, but they don't receive any initial value. This causes an area in the code where the interpreter is familiar with the variable, but it has not yet been initialized - known as the Temporal Dead Zone (or TDZ).

Yoni Weisbrod: [0:00] Hoisting refers to the fact that when I write this code here and I have these identifiers, name, flavor, animal, and test, I'm not taking the interpreter by surprise. Before it runs the code, it goes through and collects all the different identifiers. For instance, if I call this function test() before I've defined it, it'll still run properly.

[0:22] In other words, the interpreter has taken this function and hoisted it to the top of this context. Everything is hoisted, functions, variables, but they're not all hoisted in the same way. We can divide the hoisting behavior into three categories.

[0:38] We've already demonstrated that a function declaration is completely hoisted with its identifier. Var acts a little bit different to const and let, in that var is hoisted and then initialized with an undefined value, while const and let are hoisted but they're not initialized. We can demonstrate this idea by trying to reference the value before they're defined.

[1:02] You can see that if we try to reference var, nothing appears because it's undefined, but we don't get an error. Yet if we try to access const or let, you'll see that we get a reference error. It says it can't access the value before initialization. Meaning that it's aware of the identifier, but the identifier hasn't been initialized yet.

[1:24] This is what's known as the Temporal Dead Zone, the area in which the interpreter is aware of a variable, but it hasn't been initialized yet. If we try to access the variable in this zone, we will get a reference error.

[1:38] The rule about how var is hoisted applies regardless of what's on the right side. It doesn't matter if it's a function or if it's any other expression. It will still be hoisted with a value of undefined.

[1:53] If we tried using it like a function, it's not going to work because undefined is not a function. We can see that the same logic applies if we use a let or a const here. We'll have the same issue that we saw before. It will be hoisted, but it will not be initialized, so we'll get a reference error.