Understanding Hoisting in Programming Exercises

Nishit RanjanNishit Ranjan
1 min read

Explanation → It is undefined because var in hoisted and it is initialize with undefined. So a is undefined,

Internally
var a; // Hoisted (a is declared and initialized with undefined) console.log(a); // Execution phase
a = 10; // Assignment happens later

Hoisting in Function

Internally it works during the creation phase
function foo(){
console.log(“Hello from foo“);
}
foo(); // Execution Phase
after that this code is execute in execution phase, so the output is “Hello from foo“

since var is hoisted so it came to top in the scope
so internally code will execute like this
var foo
foo() → and this will be undefined because of var and hence give output as TypeError foo() is not a function
foo = function (){
console.log(“function expression“);
}

Q4 what will be output ?

it will be Reference error Cannot access x before initialization because of let keyword and let is also hoisted but it is not initialize with undefined and will be in Temporal Dead Zone.

Q5

internally
var a=1 // a is hoisted global scope and initialize with 1
function test(){
var a // iniside function a is hosted
console.log(a) // so here a is undefined
var a=2
}
test()
so the answer is undefined

0
Subscribe to my newsletter

Read articles from Nishit Ranjan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nishit Ranjan
Nishit Ranjan

Self-taught frontend developer on a mission to master JavaScript and web development. Sharing my journey, tips, and hard-learned lessons through blogs and projects.