JavaScript Hoisting

This topic is very very important in javaScript. It is an unknown behavior of javaScript. Shortly, javaScript compiler moves variables and function declarations

Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope.

Variables and constants declared with let or const are not hoisted!

JavaScript Declarations are Hoisted

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.

Hoisting applies to variable declarations and to function declarations.

function declarations are hoisted before variable declarations.

Hoisting is only possible with declaration but not the initialization. JavaScript will not move variables that are declared and initialized in a single line.

I wrote a simple code in the following code then same code is changed a little bit. number variable is declared after used in second example.

var number = 1;

console.log('number = ' + number); // display number = undefined

As you can see in the following code, number is undefined. Because it is initialized when it is declared. So, it is not hoisted.

console.log('number = ' + number); // display number = undefined
        
var number = 1;

Hoisting of function

JavaScript compiler moves the function definition at the top in the same way as variable declaration. That means, function hoisting only works with function declaration and not with function expression.

console.log(Sum(5, 5)); // 10

function Sum(val1, val2)
{
    return val1 + val2;
}

JavaScript compiler does not move function expression.

Sum(5, 5); // error

var Sum = function Sum(val1, val2)
{
    return val1 + val2;
}

As shown in the following example, square function is failing in line 2 because of function expression.

Declare Your Variables At the Top !

JavaScript compiler moves variables and function declaration to the top and this is called hoisting.

Only variable declarations move to the top, not the initialization.

Functions definition moves first before variables.

To avoid bugs, always declare all variables at the beginning of every scope.

JavaScript in strict mode does not allow variables to be used if they are not declared.

Order of precedence

Function declarations are hoisted over variable declarations but not over variable assignments.

  1. Variable assignment takes precedence over function declaration.
  2. Function declarations take precedence over variable declarations.

Leave a Reply

Your email address will not be published. Required fields are marked *