Hoisting in javascript | hoisting in js | JS hoisting | Variable before declare

Javascript Hoisting

Javascript Hoisting :

Javascript a weekply typed language, and if we are not using the ‘strict’ mode in JS, there are so many code practices which can be avoided with Javascript unlike any other languages.

One of these practise is that we can use a variable before declaring it.Yes, you heard it right;

In JavaScript, a variable can be declared after it has been used.

In other words; a variable can be used before it has been declared.


So below syntax of a program is correct;

x = 5;

console.log('x is', x); // 'x is 5'

var x ;

As we saw in previous example, there is no error thrown for the above syntax, however the variable is declared after the initialization. Here comes the most unpredicted behavior of Javascript, i.e. hoisting.

What does the hoisting means?

According to MDN, hoisting means all the declarations, irrespective of their positions are moved to the top of the function scope or the global scope .i.e actualy the behaviour in all the strongly typed langauges where the variable declarations are done in the starting of their scope, Here the difference in Javascript is that, this work is done by Javascript engine for us in Javascript. Got confused ?? So let’s have an example.

Go to your console and type

console.log( a); //ReferenceError: a is not defined

So you got a reference error, a is not defined, which seems to be correct. Since there is no variable a in your scope you got an error.

Now take Example 2 :

console.log(b) //undefined
var b;

Now  you can see , there is no reference error. Since variable has been declared and JS engine has moved it to top. So varibale has been declared but not given any value and by default if variable is not initiated in JS then it would be assigned undefined, hence the output s undefined.  According to JS the above code would be compiled as

var b;


so what does we said , the variable decalarion has been moved to top, irrespective of it’s position.

Now guess the output of example 3.

Example 3

console.log(c); //undefined
var c = 3;

You can see the output is undefined again, because the variable declartion is only moved to top not the variable assignment. and by defualt the variable would be assigned with an undefined value.

Example 3 would be interpretted as in JS engine

var c;


c = 3;

So you got the concept of the hoisting , please give your answer for the follwoing code before scroll.

console.log('First d is:' d);

var d = 9;

console.log('Second d is : ', d);

//First d is : undefined.
//Second d is : 9.