Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
hoisting
declaration

What is Javascript hoisting?

Aaron Xie

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

javascript
hoisting
declaration

CONTRIBUTOR

Aaron Xie
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring