Hoisting Explained

Meaning of Hoist in English.

It means to raise (something) by means of ropes and pulleys. So hoisting simply means lifting something up or to the top.

Meaning of Hoisting in Javascript

When the JavaScript interpreter encounters a new scope, it scans the full body of the scope and moves function, variable, and class declarations to the top of the scope. This is referred to as hoisting.

Let's dive in;

There are three types of hoisting: Variable hoisting, function hoisting, and class hoisting

Variable hoisting

There are 3 keywords used to define JavaScript variables let, var and const. Let's see the output of the following 3 code samples.

The output when you use var is undefined The output when you use let and const is ReferenceError: Cannot access 'name' before initialization.

Why this output?

The reason is that, when the JavaScript interpreter encounters a scope, it hoists the variable to the top. for var: the variables are initialized to “undefined”. Below is how the interpreter views it.

For let and const, the interpreter hoists them and leaves them uninitialized. Below is how the interpreter sees it

I hope you now understand variable hoisting. Onto the next one.

Function Hoisting

You may think the code above won't work but it will work because of hoisting. Functions can be called before they are declared, thanks to hoisting. This is how it looks after the interpreter hoists it.

Function expression hoisting

What are function expressions?

They are function stored in a variable. See code below.

Function expressions are not hoisted. Since function expressions are functions stored in a variable, the variable declaration is hoisted but the function can't be accessed before initialization.

Class Hoisting

Just like let and const, Classes are hoisted but they are not initialized. So any line of code that uses the class before the initialization results in a Reference Error.

Class expression hoisting

Same explanation as function expression hoisting

Try these exercises

0

Show Answer

4

Show Answer

2

Show Answer

8

Show Answer