Hoisting
What is Hoisting?
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope (script or function) before code execution.
Try Hoisting
Code Editor
Console Output
Click "Run" to execute your code...
Example 1: Variable Hoisting with var
console.log(x); // undefined (not ReferenceError)
var x = 5;
console.log(x); // 5
// Behind the scenes:
// var x; // Declaration is hoisted
// console.log(x); // undefined
// x = 5; // Assignment stays in place
// console.log(x); // 5
// Another example:
function test() {
console.log(message); // undefined
var message = 'Hello';
console.log(message); // Hello
}
test();Example 2: let and const - Temporal Dead Zone
// let and const are hoisted but not initialized
// console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 10;
// console.log(z); // ReferenceError: Cannot access 'z' before initialization
const z = 20;
// This is the Temporal Dead Zone (TDZ)
function example() {
// TDZ starts
// console.log(name); // ReferenceError
let name = 'John'; // TDZ ends
console.log(name); // John
}Example 3: Function Hoisting
// Function declarations are fully hoisted
sayHello(); // Works! Outputs: Hello
function sayHello() {
console.log('Hello');
}
// Function expressions are NOT hoisted
// sayGoodbye(); // TypeError: sayGoodbye is not a function
var sayGoodbye = function() {
console.log('Goodbye');
};
sayGoodbye(); // Works now: Goodbye
// Arrow functions behave like function expressions
// greet(); // TypeError: greet is not a function
const greet = () => {
console.log('Hi there!');
};
greet(); // Hi there!Example 4: Hoisting in Practice
var a = 1;
function example() {
console.log(a); // undefined (not 1!)
var a = 2;
console.log(a); // 2
}
example();
// Behind the scenes:
// function example() {
// var a; // Local variable hoisted
// console.log(a); // undefined
// a = 2;
// console.log(a); // 2
// }
// Best practice: Declare variables at the top
function betterExample() {
var x, y, z;
x = 1;
y = 2;
z = 3;
console.log(x, y, z); // 1 2 3
}Key Points
- var declarations are hoisted and initialized with undefined
- let and const are hoisted but remain uninitialized (Temporal Dead Zone)
- Function declarations are fully hoisted (can be called before declaration)
- Function expressions and arrow functions are not hoisted
- Best practice: Declare variables at the top of their scope