what is hoisting in Javascript?

Let’s take a simple example
suppose,

var a = 1

function test(){

if(!a){ var a = 2}

console.log(a)

}

test() // now call test function what do you think

/* let me guess you are thinking that output will be 1

but i’m afraid that not true

it will output 2

Why ?

*/

 

…….

at the runtime this same code will look like this

var a;

a = 1

function test(){

var a // re write the outer scope a variable. ie undefined

if(!a){a = 2} // if(!undefined) this condition gets true

so console.log(a) output 2

 

 

Leave a comment