Hoisting in JavaScript!

Shrushti Polekar
3 min readNov 19, 2020

JavaScript exhibits some different features and functionalities which sets the language apart from other programming languages! Well Hoisting is one of those features.

Everything in JavaScript happens inside an execution context. Now what is an execution context? Well execution context contains a Memory section and a Code execution section in simple terms. And It basically has two phases:

  1. Creation phase
  2. Code execution phase

Consider the following example,

First of all a global execution context is created. Whenever a JS Engine encounters any variable with var keyword it allocates memory to it with a placeholder of undefined, and for functions also memory is allocated with the actual block of code itself(as a placeholder). This takes place in the creation phase.

Creation Phase

Code Execution Phase

In this phase variable n gets its actual value. As soon as compiler encounters cube(), a new execution context is created and follows the same procedure again. Then it returns ans. Finally after this ,execution context for cube is discarded.

A stereotype definition for hoisting would be ,default behaviour which moves variables and functions to the top of execution context.

But actually what happens is,

variables and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.

Hoisting allows functions to be called even before they are declared.

Remember: variables are partially hoisted and functions are completely hoisted.

Normal functions are hoisted completely where as arrow functions and function expressions are hoisted partially.(Partially means compiler will allocate them memory with a placeholder of undefined ).

Lets have a look at this code snippet and their respective outputs and try to understand the above statements.

But if we convert the above function into an arrow function , and call it at the start, it results into a reference error!

Along with variables declared with var keyword , variables declared with let and const keywords are also hoisted! However they are in temporal dead zone.

Now what’s a temporal dead zone?

Temporal deadzone is the time since when the let variable was hoisted and is initialized with some value.

variables declared with let and const keywords are not allocated memory in global space, but they are allocated memory somewhere else. That’s a temporal dead zone.

This results into a Reference Error!

However variable a is hoisted ,it is allocated memory somewhere else but not in global memory space. If we check this in source panel we can see variable a getting hoisted.

That’s it for this blog!

Hope it helps.😃

Happy learning!🤗

--

--