Skip to content

Closure

In one line

A closure is a function that retains access to variables from its enclosing scope, even after the outer function has returned.

In simple words

A closure is created when an inner function references variables from an outer function. The inner function "closes over" those variables — it keeps them alive even after the outer function has finished running.

Closures are used for data privacy (creating private variables that can only be accessed through specific functions), partial application and currying, event handlers that need to remember state, and module patterns.

Every function in JavaScript is technically a closure because it has access to its outer scope. But the term is most useful when describing functions that intentionally capture and use outer variables.

Example

javascript
function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}
const add5 = makeAdder(5);
console.log(add5(3)); // 8 — add5 remembers x=5

The inner function closes over x and remembers it even after makeAdder returns.

How it works

  1. An outer function declares local variables.
  2. An inner function references those variables.
  3. The outer function returns the inner function.
  4. The inner function retains access to the outer variables — a closure.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary