Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
A practical guide to JavaScript scope and closures: lexical scope, the scope chain, global, function and block scope, and what a closure keeps alive. You build private state, function factories and a memoize helper, then fix the classic var-in-a-loop bug. The examples were run with Node.js 22.

If you've written JavaScript for a while, you've used closures, whether you knew it or not. They make callbacks work, keep data private in modules, and power the functional patterns in libraries such as React and Lodash. This guide is for developers who use closures but want to know why they work. Once you see how scope is decided, bugs like a variable that's suddenly undefined, or a loop that logs the same number three times, become easy to explain.
This is part 5 of the Frontend & JavaScript Fundamentals series. It builds on JavaScript data types and functions, because closures are about how functions hold on to values.
Key takeaways
- Scope is decided by where you write code, not where you call it. Inner scopes can read outer variables, never the other way round.
- A closure is a function plus the variables around it. Those variables stay alive as long as the function does.
- Use
letorconstin loops.vargives every callback the same variable.
The foundation: lexical scope
Before closure, you need scope. MDN defines scope as the current context of execution in which values and expressions are visible. JavaScript uses lexical scoping (also called static scoping).
"Lexical" means scope is decided by where you write the code, not where you call it. The layout of your source code fixes which variables each function can see.
The levels of scope
- Global scope: variables declared outside any function or block in a classic script. A top-level
varbecomes a property of the global object (windowin a browser,globalThiseverywhere). MDN notes that a top-levelletorconstdoes not. Code in an ES module or a Node.js file gets its own module scope instead. As a rule of thumb, keep the global scope as empty as you can. - Function scope: variables declared inside a function are visible only inside that function. Before ES6, this was the main boundary, and
varstill follows it. - Block scope: introduced with
letandconstin ES6. Variables declared inside a block{}(such as anifor aforloop) exist only inside that block.
const globalVar = "I am everywhere";
function outerFunction() {
const functionVar = "I am accessible within outerFunction";
if (true) {
const blockVar = "I am trapped in this block";
console.log(globalVar); // Works
console.log(functionVar); // Works
}
// console.log(blockVar); // ReferenceError: blockVar is not defined
}
The scope chain
When the engine meets a variable name, it looks it up. If the name isn't in the current scope, it looks in the parent scope. It keeps going until it reaches the global scope. If the name isn't there either, you get a ReferenceError.
This series of scopes is the scope chain. The lookup only goes one way: MDN puts it as child scopes having access to parent scopes, but not the other way round.
Closure: the time capsule
A closure is the combination of a function bundled together with references to its surrounding state, the lexical environment. That is MDN's definition. MDN also notes that closures are created every time a function is created.
In everyday terms: a closure lets a function remember the variables that were around when it was created, even after the outer function has returned.
Picturing the mechanism
Think of a function as carrying a backpack. When it's returned from another function, it keeps the variables it uses from the outer scope in that backpack. Wherever the function goes, the backpack goes too.
function createDatabaseConnection(connectionString) {
// This variable belongs to the outer scope
const status = "active";
return function query(sql) {
// This inner function 'closes over' connectionString and status
console.log(`Connecting to ${connectionString}`);
console.log(`Status: ${status}`);
console.log(`Executing: ${sql}`);
};
}
const runQuery = createDatabaseConnection("postgres://localhost:5432");
// createDatabaseConnection has finished executing here.
// Its local variables stay alive because runQuery still uses them.
runQuery("SELECT * FROM users");
// Output:
// Connecting to postgres://localhost:5432
// Status: active
// Executing: SELECT * FROM users
Here runQuery keeps a reference to connectionString and status. That persistence is closure. The example only logs text; it doesn't open a real connection.
Practical uses
Closures aren't just interview material. They help you build safer, cleaner code.
1. Data privacy and encapsulation
Classes now have true private fields with the # prefix. MDN lists them as widely available across browsers since July 2021. Closures give you the same privacy for plain functions and objects. MDN's closures guide calls this data hiding and encapsulation, and it's the basis of the module pattern.
const createCounter = () => {
// 'count' is private. Code outside can't read or change it directly.
let count = 0;
return {
increment: () => { count++; return count; },
decrement: () => { count--; return count; },
getValue: () => count
};
};
const myCounter = createCounter();
console.log(myCounter.getValue()); // 0
myCounter.increment();
myCounter.count = 100; // No error: this only adds a new, unrelated property
console.log(myCounter.getValue()); // 1
Setting myCounter.count doesn't throw; it adds an unrelated property, and the private count is untouched. That's the point: outside code has no path to the real variable.
Use this pattern for configuration objects that the rest of the app should read only through specific methods. Note that anything shipped to a browser can still be read in DevTools, so never treat a closure as a place to hide secrets.
2. Function factories
Closures let you write functions that build other functions with some arguments already set. This works well for loggers and other configuration-heavy code.
function createLogger(level) {
return function(message) {
const timestamp = new Date().toISOString();
console.log(`[${level.toUpperCase()}] ${timestamp}: ${message}`);
}
}
const infoLog = createLogger("info");
const errorLog = createLogger("error");
infoLog("System initialized");
errorLog("Connection failed");
Each logger remembers its own level. Calling createLogger twice creates two separate closures.
3. Memoization (caching)
When code repeats an expensive calculation with the same inputs, you can cache the results. Memoization is that caching, and a closure keeps the cache alive between calls.
const memoize = (fn) => {
const cache = new Map(); // The closure keeps this cache alive
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) {
console.log("Fetching from cache...");
return cache.get(key);
}
const result = fn(...args);
cache.set(key, result);
return result;
};
};
const heavyCalculation = (num) => {
// Stands in for slow work
return num * 2;
};
const efficientCalc = memoize(heavyCalculation);
efficientCalc(5); // Calculates
efficientCalc(5); // Returns from cache
efficientCalc(0); // Calculates: result is 0
efficientCalc(0); // Returns from cache, even though 0 is falsy
The earlier version checked if (cache[key]), so a result of 0, "" or false was never served from the cache. Map.has() checks whether the key exists, whatever the value is. JSON.stringify keys only suit simple arguments such as numbers and strings.
The classic pitfall: loops and var
This loop shows the difference between function scope and block scope.
// THE PROBLEM
for (var i = 1; i <= 3; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
// Output: 4, 4, 4
Why? var is function-scoped, so there is only one i for the whole loop. By the time the callbacks run, after one second, the loop has finished and i is 4. All three closures point at the same variable.
The fix: block scope
Change var to let.
// THE FIX
for (let i = 1; i <= 3; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
// Output: 1, 2, 3
MDN's for reference explains why: with let in the loop header, each iteration gets a new scope with its own copy of i. Each closure captures a different variable.
| Declaration | Scope | Each loop iteration gets its own copy? | Top-level becomes a globalThis property? |
|---|---|---|---|
var |
Function | No | Yes (in a classic script) |
let |
Block | Yes | No |
const |
Block | Yes in for...of; a counting for loop throws on i++ |
No |
Memory considerations
Closures have a cost. MDN's memory management guide explains that garbage collection frees what is no longer reachable. A closure keeps its outer variables reachable, so they can't be freed while the closure exists.
MDN's closures guide also warns against creating functions inside other functions when you don't need a closure, because it costs speed and memory. Event listeners that are never removed are a common source of leaks: the listener keeps its closure, and the closure keeps everything it references. As a rule of thumb, remove listeners and clear long-lived caches when you no longer need them.
Summary
Scope and closure explain most "why is this variable that value?" questions in JavaScript. Once you can trace the scope chain, you can predict what a function will see, keep state private, and avoid the loop bug.
Next in the series, practical DOM manipulation techniques puts closures to work: every event handler there is a closure over the app's state.
Frequently asked questions
What is a closure in JavaScript, in simple terms?
A closure is a function that remembers the variables from the place where it was created. It can still use them after the outer function has returned. MDN notes that every function creates a closure when it's created.
What is the difference between scope and closure?
Scope is the set of variables visible at a point in your code, decided by where the code is written. A closure is what lets a function keep that scope after the code around it has finished running. Scope is the rule, and closure is the result of that rule.
Why does a var loop with setTimeout log the same number?
var is function-scoped, so every callback shares one variable. By the time the callbacks run, the loop has finished and the variable holds its final value. With let, each iteration gets its own variable.
Do closures cause memory leaks?
Not by themselves. A closure keeps its outer variables alive only while the closure itself is reachable. Leaks happen when something long-lived, such as an event listener that's never removed, keeps a closure that references large data.
Should I use closures or private class fields for private state?
Both work. Private class fields with # suit code that already uses classes. Closures suit factory functions and plain objects, and they need no class syntax at all.
Sources
Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...