Hoisting in JavaScript

codesplash
1 min readApr 16, 2024

--

#2 JavaScript Series

“Hoisting is a JavaScript mechanism where all variables and function declarations are moved to the top of their scope before code execution.”

If we print variable before initialization, for /var/let/const it will work differently.

Hoisting with “var”:

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

During memory allocation

x: undefined

During code execution

When execution starts, it will encounter first x need to be printed. Since, x has undefined value, so it prints undefined, thereafter X will be assigned value 7.

Hoisting with “let” & “const”:

console.log(x);
let x = 7;

console.log(y);
let y= 9;

With let & const Uncaught Reference Error is occurred

let & const are hoisted in Temporal Dead-Zone (The period between declaration & initialization of variable of let & const)

@Guess the output

function abc (){
console.log (a);
console.log (b);
console.log (c);
var a = 5;
let b = 6;
const c = 7;
}
abc();
Undefined
Reference Error: can't access 'b' before initialization

Hoisting with function (Named function):

Hello ();
function Hello()
console.log ("Hello");
}
Hello

During memory allocation phase Hello is completely assigned the whole function body. So, it works normally with Named function.

Hoisting with Arrow function:

Hello ();
const Hello=()=>{
console.log ("Hello");
}
undefined

It now behaves as a variable not as a function. So, it will print undefined. During memory allocation phase Hello will be filled with undefined.

--

--

codesplash

Currently Moulding a New Life Through Coding || Follow me on linkedin codessmasherdeepjyotidas