Hoisting In JS

Hoisting In JS

·

2 min read

You know most hated language is JavaScript !!!

You know most loved language is JavaScript !!!

And you know according to research which is the most flexible/ powerfull language ???? It's again JavaScript

hoisting.avif

Now let's start to one of the concept of JavaScript, Hoisting

JavaScript acts very differently as compared to other language.

case 1 : var case

console.log(a);
var a = 10;

This code give error in any other language but it looks good for JavaScript. There is no error in this. It will give undefined. What happens here ???

When a code runs a global execution context is created in JavaScript callstack. JS engine first skims through the code and allocate memory to the variables and functions. That's the reason why it will give undefined.

but if

var a=10; 
console.log(a);

JS execute code line by line so, var a has got the value and it will print 10.

Now take one more example

console.log(a);
var a=10;
console.log(a);

Think !!!!!!!! Think !!!!!!!! Think !!!!!!!!

here, first console will give you undefined because the initial value of a is undefined and second console will give you 10, as the value of a will be assigned to var a.

case 2: let and const case

console.log(a);
let a = 10;

If interviewer ask then tell him that let and const are also hoisted. But it go to another scope not in global execution context, where it's value is never fetch by JS engine untill it's value has been declared and hence throws a reference error. It will go into a Temporal Dead Zone .

hoisting2.jpg

What is this new concept ???

Temporal Dead Zoneis a simple concept, when variable let and const go into hoisting and till it's value is not declared, the time span is known as temporal dead zone. Let us know with a simple example.

const add = (a,b) =>{
return a+b;
}
console.log(a);
add(4,5);
let a=10;

Here, variable a is in temporal dead zone from line 4 when it is hoisted to line 6 till it's not declared. Hope you will get the concept.