DEV Community

Cover image for Hoisting in JavaScript
Vansh Sharma
Vansh Sharma

Posted on

Hoisting in JavaScript

Let's see an example first:

var x ;
x = 50;
console.log(x);

// Output: 50
Enter fullscreen mode Exit fullscreen mode

Another Example :

x = 50;
console.log(x);
var x ;

// Output: 50
Enter fullscreen mode Exit fullscreen mode

Why in both the case output is 50. For this, you will have to understand Hoisting.

What do you understand by Hoisting in JavaScript?

According to MDN :
JavaScript Hoisting refers to the process whereby the compiler allocates memory for variable and function declarations prior to the execution of the code.

Don't worry I will explain in simple terms

Simple terms:
Hoisting means MOVING the DECLARATION part of the variables at the top of the code.

Now you might be wondering 😒 . Am I mad or what for I have written 2 caps words that too between the sentence? But these two words hold great importance.

Let's understand about some catch of this property (Hoisting).

  • Hoisting is behind a scene process done by the JS engine. It is not like you will see your variables going all the way to the top of the code.

  • It is only about ** declaring** the variables, not about initializing them.

 let x ; // Declaration
 var y ; // Declaration

let x = 6 ; // Initialization
var y = 5 ; // Initialization
Enter fullscreen mode Exit fullscreen mode
  • Initialization of the variable will only take place once that code of line is executed.

  • Using "let" before it is declared will give you a reference error.

car = "Volvo" ;
console.log(car);
let car;

// Output:  Reference error.
Enter fullscreen mode Exit fullscreen mode
  • Using "const" before it is declared will give you a syntax error.
car = "Volvo" ;
console.log(car);
const car;

// Output:  Syntax error.

Enter fullscreen mode Exit fullscreen mode
  • Only var variables will be initialized that too with "undefined" value and let and const will not be initialized at all until that line of code is executed.

  • Hoisting doesn't take place in Arrow function and class.

Quiz

var x = 10;
y = 10 ;
console.log (x+y);
var y ;

// Output : ? 
Enter fullscreen mode Exit fullscreen mode
var x = 10;
console.log(x + y);
var y = 10;

// Output: ?

Enter fullscreen mode Exit fullscreen mode
x = 10;
y=10;
console.log(x + y);
const x;
let y;

// Output: ?

Enter fullscreen mode Exit fullscreen mode

NOTE: You might be getting a little overwhelmed but don't be as a developer you should have an understanding about hoisting. A simple way to tackle this issue is just declaring the variable at the top and you are good to go.

That's all for this blog. We will meet in the next blog until then Keep Learning, Keep Growing.

Do Answer these questions in the comment section.

You can connect with me 👇

Twitter
LinkedIn

Top comments (0)