On this page

Closures: The Function’s Memory

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A closure is the combination of a function bundled together with references to its surrounding state—its lexical environment. In simpler terms, a closure gives a function access to its outer scope even after the outer function has finished executing.

This is not a feature you "enable"; it is a fundamental property of how JavaScript handles scope.

The Lexical Environment​

To understand closures, you must first understand Lexical Scoping. In JavaScript, the scope of a variable is determined by its location within the source code. When a function is defined, it "grabs" a reference to the variables available in its parent scope.

When the inner function is called, the engine looks for variables in this order:

  1. Local Scope: Variables declared inside the function.
  2. Outer (Lexical) Scope: Variables from the parent function.
  3. Global Scope: Variables at the top level of the script.

How a Closure is Born​

A closure is created every time a function is created, at function creation time. The magic happens when an inner function is returned from an outer function.


function outer() {

  let count = 0; // "Hidden" variable



  return function inner() {

    count++; // Accesses parent variable

    console.log(count);

  };

}



const counter = outer();

counter(); // Output: 1

counter(); // Output: 2

Why does this work?​

Normally, when a function finishes running, its local variables are removed from memory (garbage collected). However, because the inner function still exists (assigned to counter) and it "closes over" the variable count, the JavaScript engine keeps count alive in memory. The function remembers its birthplace.

Practical Applications of Closures​

Closures are more than a technical trivia point; they are essential for professional architectural patterns.

Data Privacy (The Module Pattern)​

JavaScript classes have private fields (#), but before they existed, closures were the only way to create truly private variables that cannot be accessed or modified from the outside.


function createSecret() {

  let secret = "I like pineapple on pizza";



  return {

    getSecret: () => secret,

    setSecret: (newSecret) => {

      secret = newSecret;

    },

  };

}



const myVault = createSecret();

console.log(myVault.getSecret()); // Access granted

console.log(myVault.secret); // undefined (Direct access blocked)

Function Factories​

You can use closures to create specialized versions of a function.


function multiplyBy(factor) {

  return function (number) {

    return number * factor;

  };

}



const double = multiplyBy(2);

const triple = multiplyBy(3);



console.log(double(5)); // 10

console.log(triple(5)); // 15

The Cost of Closures: Memory Considerations​

While closures are powerful, they come with a responsibility. Because variables in a closure are not garbage collected as long as the function is still reachable, overusing closures or creating them unnecessarily can lead to memory leaks.

If you attach a closure to a global variable or a long-lived object, the memory associated with that closure's lexical environment will never be freed. In expert-level development, always be mindful of how long your closures stay in scope.

Summary​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Hoisting & The Temporal Dead Zone

Next

Memory Management