Beginner LevelJavaScript & TypeScript
What is hoisting in JavaScript and how does it affect functions and variables?
❓ Interview Prompt: Explain how the JavaScript engine hoists function declarations vs var vs let/const during the creation phase.
Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their containing scope during the compilation/creation phase before execution.
How Different Declarations Hoist:
1
Function Declarations: Completely hoisted with implementation intact. Can be invoked before declaration.
2
`var` variables: Hoisted and initialized with
undefined. Accessing before declaration returns undefined.3
`let` and `const` variables: Hoisted into the Temporal Dead Zone (TDZ) but NOT initialized. Accessing before declaration throws a
ReferenceError.4
Function Expressions / Arrow functions: Variable declaration hoists, but function assignment does not.
Code Implementation Example
javascript
// 1. Function Declaration (hoisted completely)
sayHello(); // "Hello!"
function sayHello() { console.log("Hello!"); }
// 2. var variable (hoisted as undefined)
console.log(x); // undefined (no error!)
var x = 10;
// 3. let / const (hoisted into TDZ)
// console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 20;
// 4. Function expression with var
// fn(); // TypeError: fn is not a function (it's undefined!)
var fn = function() { console.log('Hi'); };💡Complete function declaration hoisting vs var undefined hoisting vs let TDZ error.
🎯 Interview Key Takeaway
Function declarations can be called before definition. var hoists as undefined; let and const hoist into the Temporal Dead Zone.
#Hoisting#Scope#TDZ#Beginner
Back to all JavaScript & TypeScript Questions→