Closures & Scopeeasy
Explain hoisting
What is hoisting? How does it differ for `var`, `let`/`const`, and function declarations vs expressions?
Asked at Amazon, Apple
Answer
// Usage // Hoisting: declarations are moved to the top of their scope // during the compile phase. Only the declaration is hoisted, // not the initialisation. // var — hoisted and initialised to undefined console.log(x) // undefined (no error) var x = 5 console.log(x) // 5 // let/const — hoisted but NOT initialised (Temporal Dead Zone) console.log(y) // ReferenceError: Cannot access 'y' before init let y = 10 // Function declarations — fully hoisted (name + body) greet() // "Hello!" — works before the declaration function greet() { console.log('Hello!') } // Function expressions — only the variable is hoisted sayHi() // TypeError: sayHi is not a function var sayHi = function() { console.log('Hi!') } // Key rule: prefer const/let and declare before use.