Closures (In JavaScript and Beyond)

In short: A closure is a function bundled together with the variables from the scope where it was defined, so it can keep accessing those variables even after that outer scope has finished running. Closures enable data privacy, callbacks, and many JavaScript patterns.

A closure is a function that accesses a variable "outside" itself. For example:

const message = 'The British are coming.'; function sayMessage(){ alert(message); // Here we have access to message, // even though it's declared outside this function! }

We'd say that message is "closed over" by sayMessage.

One useful thing to do with a closure is to create something like an "instance variable" that can change over time and can affect the behavior of a function.

// Function for getting the id of a dom element, // giving it a new, unique id if it doesn't have an id yet const getUniqueId = (() => { let nextGeneratedId = 0; return element => { if (!element.id) { element.id = `generated-uid-${nextGeneratedId}`; nextGeneratedId++; } return element.id; }; })();

Why did we put nextGeneratedId in an immediately-executed anonymous function? It makes nextGeneratedId private, which prevents accidental changes from the outside world:

// Function for getting the id of a dom element, // giving it a new, unique id if it doesn't have an id yet let nextGeneratedId = 0; const getUniqueId = element => { if (!element.id) { element.id = `generated-uid-${nextGeneratedId}`; nextGeneratedId++; } return element.id; }; // ... // Somewhere else in the codebase... // ... // WHOOPS--FORGOT I WAS ALREADY USING THIS FOR SOMETHING nextGeneratedId = 0;

Frequently Asked Questions

What is a closure?

A closure is a function that remembers the variables from the scope in which it was created, retaining access to them even after that outer function has returned.

What are closures used for?

Private state and data hiding, factory functions, callbacks and event handlers, and partial application or currying.

Do closures cause memory leaks?

They can if a closure keeps references to large objects longer than needed, but properly scoped closures are freed by the garbage collector once nothing references them.

Last updated: June 17, 2026

. . .