What is Variable Hoisting in JavaScript ?

Let’s try to understand Variable Hoisting in JavaScript with the help of an example.

var a = 100;

When the JavaScript engine begins to execute the above code, during the compilation phase it allocates a memory to the variable a. Not just variable a but to every variable in the JavaScript code a memory is assigned.

During the execution phase it executes the code where it’s assigned a value of 100.

In between, when the memory has been assigned to the variable and the variable has not been assigned a value, the default value assigned to variable a is undefined.

So, if you try to access the variable before it’s declaration it will print the value undefined and not throw an error.

console.log(a); // prints undefined
var a = 100;

This is called Variable Hoisting in JavaScript.