Categories
ECMAScript Javascript

Hoisting

Hoisting term refers to way variables are declared in javascript. if we declare variable with VAR as keywords they will be hoisted at beginning of script during compilation. That means declaration will automatically move to start of file in global scope. LET keyword does not support concept of hoisting. Hence if we want to declare variable with local scope we must use LET.

/**
 * To demonstrate the var variables support hoisting and let variables do not.
 * hence if var is declared inside blocks they are still accessible outside due to hoisting effect.
 * As a part of hoisting all declarations are moved to the beginning of function or file.
 */


function sayHi(){
for(var i=0;i<5;i++){
	var message1 = "I am Tina";
	console.log(i+" : inside for loop message1 ::"+message1);
	let message2 = "I am Hina";
	console.log(i+" : inside for loop message2 ::"+message2);
}
console.log(i+" : message1 :: "+message1);
//since  i, message are declared by var, they support //hoisting, hence they live even outside of block where they were declared.

//console.log("message2 :: "+message2) 
//since message2 is declared by let, it was not hoisted hence //it lives upto end of //the for block.
}
sayHi();

Output

Leave a comment

Design a site like this with WordPress.com
Get started