Hoisting
Overview
Hoisting is a JavaScript mechanism where variable and function declarations are moved (or 'hoisted') to the top of their scope before code execution.
Because of hoisting, you can theoretically call a function before you even write the code for it in the file!
Syntax
Function declarations are fully hoisted. The JS engine loads the entire function into memory during the creation phase.
// Calling the function BEFORE it's defined
greet(); // Outputs: "Hello there!"
function greet() {
console.log("Hello there!");
}With var, the declaration is hoisted, but the initialization (assigning 22) is left behind. So it exists in memory as undefined until line 2 runs.
console.log(age); // Outputs: undefined
var age = 22;Common Pitfalls
- Assuming Arrow Functions are hoisted. If you assign an arrow function to a
var,let, orconst, it behaves like a normal variable and is NOT fully hoisted like a traditionalfunction().
Interview Questions
Yes, they are! However, unlike 'var' which is initialized as 'undefined', 'let' and 'const' remain uninitialized in a state called the Temporal Dead Zone. Accessing them before declaration throws a ReferenceError.
Real-World Example
In older codebases, developers often put a massive init() function call at the very top of the file, and then defined all their helper functions below it, relying purely on hoisting.
// Starts the app instantly
initApplication();
// ... 500 lines of helper functions below ...
function initApplication() { /* ... */ }Check Your Knowledge
Test your understanding of Hoisting with these quick questions.