JavaScript Tutorial

Javascript Hoisiting

It is a mechanism in JavaScript that moves the declaration of variables and functions at the top. So, in JavaScript we can use variables and functions before declaring them. This is known as hoisting.

This hoisting is applicable only for declaration not initialization. It is required to initialize the variables and functions before using their values.

Variable hoisting

In this type of hoisting means the JavaScript engine moves the variable declarations to the top of the script. The following example declares the counter variable and sets its value to 1.

However, the first line of code will not cause an error because the JavaScript engine moves the variable declaration to the top of the script. Technically, the code looks like the following in the execution phase:-

In technical terms, during the creation phase of the global execution context, the JavaScript engine places the variable counter in the memory and initializes its value to undefined.

Input:-

Output:-

Function hoisting

Like variables in javascript, the engine also hoists the function declarations. It moves the function declarations to the top of the script. For example:

In the above example, we called the add() function before defining it. The above code is equivalent to the following:

In Javascript, during the creation phase of the execution context, engine places the add() function declaration in the heap memory. To be precise, the JavaScript engine creates an object of the Function type and a function reference called add that refers to the function object.

Input:-

Output:-

 

Go back to Previous Course