JavaScript Closures, Scope, and Hoisting: Deep Dive With Code Examples
Closures, scope chains, and hoisting are the most misunderstood JavaScript concepts. This deep dive explains each with practical code examples and common interview questions.
These three concepts are the foundation of JavaScript. Master them to debug anything.
Scope
JavaScript has three scope types: global, function, and block (let and const).
if (true) {
var x = 1; // function-scoped leaks out
let y = 2; // block-scoped stays inside
const z = 3; // block-scoped stays inside
}
console.log(x); // 1
console.log(y); // ReferenceError
Hoisting
var declarations are hoisted to the top, but NOT their values. let and const are hoisted but in a temporal dead zone.
console.log(a); // undefined (hoisted)
console.log(b); // ReferenceError (TDZ)
var a = 1;
let b = 2;
Closures
A closure is a function that remembers variables from its outer scope even after the outer function has returned.
function createCounter() {
let count = 0;
return {
increment: () => ++count,
getCount: () => count
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
Closure Pitfall: Loops
Using var in a for loop with setTimeout creates closures that all share the same i. Use let instead.
Practical Use: Data Privacy
Closures create private variables — the module pattern in ES5.
Deepen your JavaScript skills. See our services.
Written by M Daniyal Amjad Ali
Full Stack Software Engineer with 5+ years of experience. Expert in Next.js, React, Node.js, and Prisma. 100+ projects delivered worldwide.