How do closures function in JavaScript?

Can you explain JavaScript closures to a person who understands the related concepts, like functions and variables, but can't comprehend closures themselves?

I checked out the Scheme example on Wikipedia, but sadly it wasn't helpful.

7 Likes

JavaScript closures can sometimes seem elusive, even if you have mastered other fundamental concepts such as functions and variables. To demystify closures, it’s essential to first understand the notion of lexical scope in JavaScript.

A closure in JavaScript is essentially a function that remembers the environment—i.e., the scope—in which it was created. Closures are created every time a function is declared, not when it is executed. When a function is defined, it keeps track of all the variables that are within its scope at the very point of definition.

A Practical Example of Closures

Consider the following code snippet to see how closures work in practice:

function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    console.log('Outer Variable:', outerVariable);
    console.log('Inner Variable:', innerVariable);
  };
}

const newFunction = outerFunction('outside');
newFunction('inside');

Explanation:

  • outerFunction: When called, this function returns innerFunction, but it does not lose track of outerVariable. Instead, it creates a closure.
  • innerFunction: When innerFunction is later executed via newFunction, it maintains access to both outerVariable and innerVariable. Hence, it can log both variables to the console.

Key Concepts

  1. Encapsulation: Closures allow data to be encapsulated and preserved within the scope of the function, making them useful for data privacy.

  2. Stateful Functions: Functions can carry and manipulate their state over time, retaining values between function calls.

  3. Practical Use:

    • Maintaining state in an asynchronous environment like callbacks in event-driven programming.
    • Developing factory functions that return other functions with preserved states.

Understanding closures enables you to write more efficient and modular code. They offer a way to bind the execution environment to a function, providing rich and powerful ways of working with scopes and state.

1 Like

Hey there!

A closure is a function that retains access to its lexical scope, even when executed outside that scope. Here’s a quick example:

function makeCounter() {
  let count = 0;
  return function() {
    count++;
    return count;
  };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2

The innerFunction remembers the environment where it was created, i.e., access to count.

4 Likes