Hoisting in JavaScript
Hoisting is JavaScript's default behavior of moving declarations to the top of their scope during the compilation phase. Understanding hoisting is crucial for avoiding unexpected behavior in your code.
Variable Hoisting
// Variable hoisting with var
console.log(x); // undefined (not ReferenceError)
var x = 5;
// What's actually happening:
var x;
console.log(x);
x = 5;
// let and const are hoisted but not initialized
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 5;Function Hoisting
// Function declaration hoisting
sayHello(); // "Hello!" (works)
function sayHello() {
console.log("Hello!");
}
// Function expression hoisting
sayGoodbye(); // TypeError: sayGoodbye is not a function
var sayGoodbye = function() {
console.log("Goodbye!");
};
// Arrow functions (same as function expressions)
sayHi(); // TypeError: sayHi is not a function
var sayHi = () => {
console.log("Hi!");
};Class Hoisting
// Class declarations are not hoisted
const p = new Person(); // ReferenceError
class Person {
constructor() {
this.name = "John";
}
}
// Class expressions are not hoisted either
const Animal = class {
constructor() {
this.type = "unknown";
}
};Temporal Dead Zone (TDZ)
// TDZ with let and const
{
console.log(x); // ReferenceError
let x = 1;
}
// Multiple declarations
var x = 1;
{
console.log(x); // ReferenceError (TDZ)
let x = 2;
}
// const behavior
console.log(API_KEY); // ReferenceError
const API_KEY = "abc123";Function and Variable Precedence
// Function declarations take precedence over variable declarations
console.log(foo); // [Function: foo]
var foo = "bar";
function foo() {
return "foo";
}
// But variable assignments still override
console.log(foo); // "bar"Common Interview Follow-up Questions
- Why does JavaScript hoist declarations?
- How does hoisting differ between var, let, and const?
- What is the Temporal Dead Zone?
- How does hoisting work with function expressions vs declarations?
Best Practices
- Always declare variables at the top of their scope
- Use const and let instead of var
- Declare functions before using them
- Be aware of hoisting when using function declarations
- Understand TDZ when using let and const