Stop guessing what your variables can see: closures and scope, explained plainly
A closure is a function plus the environment it was born in. This guide follows MDN's Closures guide and the JavaScript execution model: lexical scope, var vs let/const, function factories, private variables, the scope chain, the famous var-in-a-loop trap, and the cost of creating functions for nothing.

First, the boundaries of this guide. The site already has a practical guide to Promises and async/await, about the ways to write code that waits for a result to come back; this guide is not about waiting for results, it is about the life of a variable: where it is written in the code, how long it lives, and who can see it. There is also a practical guide to CSS Grid layout, about arranging a page; this guide is not about layout, only about the two JavaScript ideas that trip people up most often: scope and closures. The "Greenstone Cafe" used below is a fictional practice project: a small web tool that takes orders for a street-side cafe — customers order, pick a size, add extras, and the program works out the price and counts loyalty visits. Every operation, code sample, and number built around it was invented to explain the technique, not a real record. All syntax and behavior of scope and closures comes from MDN's Closures guide and the JavaScript execution model reference page; see each article's meta information and evidence record for sources. MDN's own examples, such as the Mozilla name, the makeAdder adder, and the form with three hints, are the documentation's examples, not real user data.
Step 1: A variable is looked up where it is written — that is lexical scope
In JavaScript, a variable is found by position, not by time. MDN puts it this way: lexical scoping means the parser resolves variable names by the location where a variable is declared in the source code. An inner function can see the outer function's variables, not because it was born while the outer function was running, but because it is written inside the outer function. MDN's first example makes this clear: the init function first declares a local variable name with the value Mozilla, then defines a displayName function inside it that prints name. When init is called, displayName runs and console.log prints Mozilla. displayName has no local variables of its own, but because it is written inside init, it can see all of init's variables. That is what it means for nested functions to have access to outer scope: what you can see depends on where you are written.
The reverse is also true: code written outside cannot see what is written inside. The name inside init cannot be touched from outside init. Scope is a one-way door: the inside can see the outside, the outside cannot see the inside. Many beginners declare variables everywhere and use them everywhere, assuming that "it is all in the same file." The first lesson of lexical scope is that a file is not a scope — where a variable is written, and how many levels of braces it is nested inside, decides who can see it.
Step 2: var has only two scopes, and a block's braces cannot stop it
Before ES6, JavaScript variables had only two kinds of scope: function scope and global scope. A variable declared with var belongs either to a function or to the global scope. This is especially easy to get wrong for people coming from C or Java, where braces create scopes. MDN gives a direct example: inside an if statement, if Math.random() is greater than 0.5, var x equals 1, otherwise var x equals 2, and then x is printed outside the if. By C-language intuition, that print should fail, because x's scope is only inside the if's braces. But in JavaScript it does not fail — x prints fine, because var declarations do not recognize blocks, and the two var x declarations are really the same global variable.
This behavior is not a small quirk; combined with closures, it later causes a classic bug. Remember the conclusion: var only recognizes functions and the global scope, not blocks. Whenever you see var, ask one more question: which function does this variable belong to? If it is written outside every function, it is global, and every script on the page can touch it.
Step 3: let and const finally make braces count
ES6 introduced let and const, and these two declarations finally gave blocks scope. Take the same if example and change var to const, and printing x outside the if throws a ReferenceError: x is not defined. MDN's own words are that in ES6, blocks are finally treated as scopes, but only if you declare variables with let or const. ES6 also introduced modules, which are another kind of scope. Closures can capture variables in all of these scopes — function scope, block scope, and module scope, none left out.
For anyone writing new code, the conclusion is simple: use const by default, use let only when the value needs to change, and avoid var whenever you can. This is not a style preference; the scope rules themselves changed. With let and const, the visible range of a variable lines up with the code's indentation: written inside a pair of braces, it is only valid inside those braces. Readers no longer have to guess who a variable belongs to — they can see it at a glance.
Step 4: A closure is a function plus the environment it was born in
Once scope is clear, a closure is just one sentence. MDN's definition is: a closure is the combination of a function and the lexical environment within which that function was declared. That environment consists of any variables that were in scope at the time the closure was created. Look at MDN's makeFunc example: the outer function makeFunc declares const name equal to Mozilla, then defines the inner function displayName, which prints name, and finally returns displayName. Calling makeFunc gives you myFunc, and calling myFunc still prints Mozilla. At first glance this seems unintuitive: in other languages, a function's local variables disappear when the function finishes, so name should be gone. But in JavaScript it is still there, because the displayName function instance keeps holding on to the lexical environment it was born in, and name lives in that environment, so when myFunc is called, name is still available.
The execution model reference page says this even more plainly: whenever a function is created, it also memorizes internally the variable bindings of the current running execution context, and then these variable bindings can outlive the execution context. The function finished, the stack frame was popped, but the variable stays alive because the closure is holding on to it. That is the essence of a closure: it is not advanced magic, it is just "a function packs up the environment it was born in and takes it along." Once you understand this sentence, every use of closures and every closure bug can be derived from it.
Step 5: Function factories — one mold, many different functions
The most common legitimate use of closures is the function factory. MDN's makeAdder example is only a few lines, yet it explains the value of closures completely: makeAdder takes one argument x and returns a new function; the returned function takes an argument y and returns x plus y. makeAdder(5) makes add5, makeAdder(10) makes add10. add5(2) is 7, add10(2) is 12. add5 and add10 share the same function body definition, but store different lexical environments: in add5's environment x is 5, in add10's environment x is 10. MDN's own words are that they share the same function body definition, but store different lexical environments.
This is the first benefit of closures: binding data to the function that operates on that data. MDN draws a parallel with object-oriented programming: objects associate data with the methods that operate on it, while closures associate data with the function that operates on it. So anywhere you would normally use an object with only a single method, you can use a closure instead. Such situations are especially common on the web: binding a click to a button, a hint to an input field, a handler to a list item — each callback is a piece of code that runs only when the user triggers it, and the closure lets it still remember the variables from when it was born.
Step 6: Text-size buttons — what closures look like on a real page
MDN grounds closures on a real page with text-size buttons. The idea is that the body text uses 12px and headings use the relative em unit, so changing the body font size resizes the whole page's text along with it. The JavaScript is a makeSizer function: it takes a size and returns an arrow function that sets document.body.style.fontSize to that size in pixels. makeSizer(12), makeSizer(14), and makeSizer(16) produce three functions — size12, size14, and size16 — which are attached to three buttons' onclick handlers. Click the 12 button and the text becomes 12px; click the 16 button and it becomes 16px.
The three button functions look identical; the only difference is the size each one is holding on to. This is the everyday shape of a function factory: write the mold once, and mass-produce functions carrying different data. The Greenstone Cafe order page could be written the same way: a makeSizeButton function takes a size option such as "large, plus 4 yuan," and returns a click handler that sets the order's size to large and adds 4 yuan to the price. The size is fixed when the function is born, and used when the button is clicked. Closures here are not showing off — they are the simplest way to let "each button remember what it is for."
Step 7: Private variables — what outsiders cannot touch is truly yours
The second legitimate use of closures is private variables. Before classes arrived, JavaScript had no native way to declare private methods, but closures could emulate them. MDN's counter example is the standard pattern: an immediately invoked function first declares let privateCounter equal to 0, then defines an inner function changeBy that adds or subtracts, and finally returns an object carrying three public methods — increment, decrement, and value. increment calls changeBy(1), decrement calls changeBy(-1), and value returns the current privateCounter. Running it gives: 0 at first, 2 after two increments, 1 after one decrement.
The key point is that privateCounter and changeBy cannot be touched from outside. The three public methods share one lexical environment, which holds these two private members; the outside world can only reach them indirectly through the three methods, and cannot change them or see the implementation. MDN notes explicitly that these three public functions form closures that share the same lexical environment. If you want another independent counter, use the makeCounter function factory: each call creates a new lexical environment, so counter1 and counter2 keep their own privateCounter values independent of each other. After two increments counter1 reads 2, while counter2 still reads 0. The cafe's loyalty visits could be counted this way: one counter per member, visits only go up, the outside can only read the count and cannot change it directly — the only way to change it is through the proper "add one visit" interface.
Two kinds of sharing must be told apart here. Three public methods sharing one environment is "one counter, three keys"; two counters each independent is "two counters, one key each." The first is the module pattern, the second is the function factory. Failing to tell these two apart is why many people get lost reading closure code: first ask "do these functions share one environment," then ask "which call created this environment," and the answer becomes clear.
Step 8: The scope chain — an inner function can see all the way out
A closure can see not only its direct outer scope, but all outer scopes. MDN's sum example works this out with arithmetic: the global scope first declares const e equal to 10; sum(1) returns a function, passing 2 returns another, passing 3 another, and passing 4 reaches the innermost function, which returns a plus b plus c plus d plus e. sum(1)(2)(3)(4) is 20: 1 plus 2 plus 3 plus 4 plus 10 equals 20. Each nested function can access the outer functions' variables, and MDN's own words are that closures have access to all outer scopes.
This example also carries a note on writing style: MDN gives both an anonymous-function version and a named-function version with sum2, sum3, and sum4, with the same result. The named version has the advantage that the names show up in the stack when debugging; the anonymous version is shorter to write. Which to choose is a team habit; but either way, the rule is the same: variables are looked up layer by layer outward from where they are written, all the way to the global scope, and an error is thrown if they are not found. Closures can also capture block-scoped and module-scoped variables. MDN's example is a function that wraps const y equal to 6 in braces and stores an arrow function reading y in an outer getY — after leaving the block, printing y directly gives undefined, but calling getY() still returns 6. The module example is the same: myModule.js declares let x equal to 5 and exports getX and setX; after another module imports them, setX(6) followed by getX() returns 6. The block finished, the module variable was never exposed directly, and the closure can still read and write it.
Step 9: var inside a loop is the most famous closure trap
As noted earlier, var does not recognize blocks. Combined with closures, this causes the most famous bug in JavaScript history. MDN's form example is: a page has three input fields — email, name, and age — and focusing each field should show its matching hint below. setupHelp stores three hints in a var helpText array, then loops with var i and var item, attaching an onfocus callback to each input that shows item.help. When you run it, no matter which field you focus, the age hint is always shown.
The cause is the closure definition biting back: the three onfocus callbacks are all closures, and they all hold on to the same single lexical environment of setupHelp, which contains only one item variable. By the time the loop has finished, item already points to the last entry in helpText, so when the three callbacks run later, they all read the last entry. MDN's own words are that three closures have been created by the loop, but each one shares the same single lexical environment, which has a variable with changing values (item); because the loop has already run its course by that time, the item variable has been left pointing to the last entry in the helpText list.
There are three fixes, in MDN's order. The first is to use a function factory to create one more closure: makeHelpCallback(help) creates a new environment on each call, where help is the matching hint, so each of the three callbacks holds its own. The second is to wrap the current item in an immediately invoked function. The third is the simplest: change var to let or const, so each loop iteration gets its own block scope and item is new every time. Modern code should pick the third, or skip the for loop entirely and use for...of or forEach, where item is new on every iteration and the closure problem disappears. Remember the test: when a loop binds callbacks, first check whether the variable is var or let — var shares one, let makes a new one each time.
Step 10: Closures are not free — do not create functions for nothing
Closures are useful, but they are not free. MDN warns at the end of the guide: each function instance manages its own scope and closure, so it is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption. The example is a MyObject constructor that defines getName and getMessage inside the constructor — every time an object is created with new, the two methods are created again. Moving them onto the prototype, MyObject.prototype.getName, lets all objects share one method definition, created only once no matter how many objects are made. MDN adds that redefining the whole prototype is not recommended; the right approach is to append to the existing prototype one method at a time.
The substance of this rule is: only create a closure when you need it to hold on to an environment. When each object needs to remember its own data, use a closure or an instance property; when the behavior is shared, use the prototype. In the cafe example, each order needs to remember its own items and price, so a closure or fields will do; but "work out the total" is the same behavior for every order, so putting it on the prototype is enough — there is no need to copy it for every order. There is also the opposite kind of waste: a closure holds on to its environment and never lets go, so the variables in that environment stay alive. If a closure stays attached to an event listener for a long time, the large object it holds on to can never be freed, and the page gets slower the longer it runs. When you are done with a closure, remember to unbind it — call removeEventListener when the listener is no longer needed, and do not let it keep holding on.
Step 11: 84 closure incidents in one quarter — check yourself against the chart

The chart above shows a fictional quarter for the Greenstone Cafe project: 84 incidents related to closures and scope in total. A var shared inside a loop, so three buttons all became the last one: 30, or 35.7%, the largest group; two counters' state mixed up, so one member's visits were counted under another member: 20, or 23.8%; a private variable changed directly from outside, bypassing the proper interface: 14, or 16.7%; methods rebuilt on every new object, so the page got slower the longer it ran: 12, or 14.3%; a closure never letting go, so a large object could not be freed: 8, or 9.5%. 30 + 20 + 14 + 12 + 8 = 84, and the books balance. These numbers are invented examples, meant to show at a glance that the first two groups together are almost sixty percent — and that they are the same root cause in different spellings: failing to tell "one environment" from "a new environment each time."
Checklist: after writing code with closures, tick each item
First, declare variables with const by default, use let only when the value needs to change, and avoid var whenever you can. Second, for every variable an inner function uses, first ask which layer it is written in and which scope it belongs to. Third, a function factory creates a new environment on every call, so add5 and add10 do not affect each other; to share, let several methods use the same environment. Fourth, private variables are only read and written through the public methods that are returned — the outside cannot touch them directly. Fifth, when a loop binds callbacks, first check whether the variable is var or let: var shares one, let makes a new one each time, and when in doubt use for...of or forEach. Sixth, do not create functions for nothing where no closure is needed; put shared behavior on the prototype. Seventh, unbind a closure holding a large object when you are done with it, and do not let a listener keep holding on forever. Eighth, when debugging a closure, ask two questions: do these functions share one environment? And which call created this environment? If any item cannot be answered, go back to its section and read it again — that is worth more than memorizing ten more APIs.
Comments (0)
Sources
Related articles
Flexbox lays things out in one direction at a time, and when it is done right, the nav bar, the card wall, and the cart rows all behave. This guide follows MDN's Basic concepts of flexbox, Aligning items in a flex container, and Controlling ratios of flex items along the main axis: the two axes, containers and items, direction and wrapping, free space, the three flex properties, alignment on both axes, and gaps and auto margins.
One order is one object: table, dishes, total, paid — all filed by label. This guide follows MDN's Working with objects, JSON, and Object references: object literals, dot vs bracket notation, adding and deleting properties, for...in with hasOwn, methods and this, getters and setters, references vs copies, Object.assign and friends, null-prototype objects, JSON's strict rules, and stringify and parse with their number-precision trap.
You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.