Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope before code execution. This allows calling functions before their declaration in the code. 📈
Hoisting is a JavaScript feature that often confuses beginners. Understanding this concept helps write code without unexpected errors. 👨💻
JavaScript “hoists” variable and function declarations to the beginning of their scope:
// Can be called before declaration
sayHello(); // 'Hello!'
function sayHello() {
console.log('Hello!');
}// Fully hoisted
declared(); // Works ✅
function declared() {
return 'Result';
}// Only variable is hoisted
// expressed(); // Error! ❌
var expressed = function() {
return 'Result';
};// This works thanks to hoisting
console.log(sum(2, 3)); // 5 ✅
function sum(a, b) {
return a + b;
}// Variables are hoisted but not initialized
console.log(x); // undefined (no error!)
var x = 5;
// Functions are fully hoisted
greet(); // 'Hello!' ✅
function greet() {
console.log('Hello!');
}// JavaScript does this before execution:
// 1. var hoisted; // undefined
// 2. function declared() { return 'Works'; }
// 3. Then executes code
console.log(hoisted); // undefined
var hoisted = 'Value';
console.log(declared()); // 'Works'
function declared() {
return 'Works';
}// Hoisting works in each scope
function example() {
// In this scope hoisting also works
console.log(test()); // 'Works' ✅
function test() {
return 'Works';
}
}// Fully hoisted — can be called before declaration
earlyCall(); // Works ✅
function earlyCall() {
console.log('Called early');
}// Not hoisted like Function Declaration
// earlyArrow(); // Error! ❌
var earlyArrow = () => {
console.log('Arrow function');
};// ❌ Thinking variable immediately has value
console.log(value); // undefined, not 10!
var value = 10;
// ✅ Actually JavaScript does:
// var value; // undefined
// console.log(value); // undefined
// value = 10;// ❌ let and const are also hoisted, but not initialized
// console.log(block); // ReferenceError!
// let block = 'value';
// ✅ var is hoisted and initialized as undefined
console.log(oldStyle); // undefined
var oldStyle = 'value';Understanding hoisting helps write more predictable code and avoid errors with declaration order. 😊
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪