What is Javascript hoisting?

Hoisting is Javascript’s default behavior of moving all declarations to the top of their functional scope.

Hoisting variables

The basic programming fundamental of many languages is to declare a variable and then initialize it; however, JavaScript works differently. JS hoists the declaration of a variable up and allows it to be used. This way, a variable can be declared after it has been used.

svg viewer

Let’s take a look at an example.

var a = 1;
var b = 2;
var c = 3;
console.log(a + " " + b + " " + c);

The above code runs as expected, printing the values of a, b and c in chronological order. However, what happens when we declare a variable after the console log?

var a = 1;
var b = 2;
c = 3;
console.log(a + " " + b + " " + c);
var c;

We get the same result. The code above is a simple example of hoisting where the variable declaration of c is brought to the top of the code and assigned the value of 3. What happens when we initialize c and assign its value after the console log?

var a = 1;
var b = 2;
console.log(a + " " + b + " " + c);
var c = 3;

As you can see, we get an undefined value. This is because hoisting only moves up declarations, not value assignments. So, when the console logs, c will have been initialized, but will not yet have been assigned a value.

Hoisting functions

Hoisting works for functions as well.

func();
function func() {
var a = 1;
var b = 2;
var c = 3;
console.log(a + " " + b + " " + c);
}

While hoisting can sometimes be useful, it will also slow down the loading speed of the browser; so, it’s important to be careful when using this functionality.

Copyright ©2024 Educative, Inc. All rights reserved