Problem Statement
What is hoisting in JavaScript? Explain how it works for variables and functions with examples.
Explanation
Hoisting is JavaScript’s behavior of moving declarations to the top of their scope during compilation.
Function declarations are hoisted with their definitions, so you can call them before they appear.
var declarations are hoisted and initialized to undefined.
let and const are hoisted but not initialized, so accessing before declaration causes a ReferenceError (temporal dead zone).
Code Solution
SolutionRead Only
// VAR HOISTING
console.log(name); // undefined (not error)
var name = 'John';
console.log(name); // 'John'
// What JavaScript actually does:
var name; // Declaration moved to top
console.log(name); // undefined
name = 'John'; // Assignment stays here
console.log(name); // 'John'
// LET/CONST HOISTING (Temporal Dead Zone)
// console.log(age); // ReferenceError!
let age = 25;
// console.log(PI); // ReferenceError!
const PI = 3.14;
// FUNCTION DECLARATION HOISTING
greet(); // 'Hello!' - Works before definition!
function greet() {
console.log('Hello!');
}
// FUNCTION EXPRESSION - NOT HOISTED
// sayHi(); // TypeError: sayHi is not a function
var sayHi = function() {
console.log('Hi!');
};
// What happens:
var sayHi; // Only variable hoisted as undefined
// sayHi(); // TypeError: undefined is not a function
sayHi = function() { // Function assigned here
console.log('Hi!');
};
// ARROW FUNCTION - NOT HOISTED
// welcome(); // ReferenceError
const welcome = () => {
console.log('Welcome!');
};
// TRICKY EXAMPLE
var x = 1;
function test() {
console.log(x); // undefined (not 1!)
var x = 2;
console.log(x); // 2
}
// Why undefined?
function test() {
var x; // Local x hoisted, shadows global x
console.log(x); // undefined
x = 2;
console.log(x); // 2
}