Variable Hoisting in Javascript.

Javascript is weird. In Javascript you can use a variable before declaring it. In other words, A variable can be declared after it has been used.

for example:

x = 10;
var x;

This is a perfectly valid javascript code. It is possible by a concept in javascript called variable hoisting. In simple terms hoisting is javascript’s behavior wherein variables and function declaration are moved at the top of the current scope before execution.

Now a thing to note here is that variables declared with let and const are neither hoisted nor are variable initializations just the declaration is hoisted.

In the case of functions arrow functions are not hoisted. So, if you try to use an arrow function before its declaration it will throw you a Reference error.

I hope this clears what hoisting means in Javascript. One of the major advantages of variable hoisting is that you don’t need to care where your functions are declared in the current scope. Before the execution of your code all declaration would be moved at the top of the code. So you can call your functions before its declaration.

Leave a Reply