iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🤐

What is the Purpose of Closures in JavaScript?

に公開

Purpose of the Article

I suddenly thought, "Wait, what are closures for again?" so I've put together a brief summary as a memo.
Beyond that, I wrote this article in the hope that it would be helpful to others who, like me, aren't quite sure why closures are necessary.

What you can gain from this article

  • You might find an answer to "What are closures for?"
  • You might get a clearer idea of "What is a closure?"

Conclusion

The biggest advantage of closures is that they prevent global pollution and improve code maintainability.

What is a Closure?

A closure is a mechanism that allows a function to maintain state by continuing to reference a specific variable within that function.
Since JavaScript uses garbage collection for memory management, it preserves the memory state as long as a variable continues to be referenced inside a function.
Because of this, the variable's data remains without being re-initialized, causing the function to behave as if it is holding state.

const createCounter = () => {
    let count = 0;
    return function increment() {
        // The `increment` function references the `count` variable defined in the `createCounter` function's scope
        count = count + 1;
        return count;
    };
};

// The result of executing createCounter() is the `increment` function defined inside
const myCounter = createCounter();
// The result of executing the myCounter function is the evaluation result of `count`
console.log(myCounter()); // => 1
console.log(myCounter()); // => 2

Closures Define New Functions

Furthermore, a new function is defined every time a closure function is executed. Therefore, when you assign a closure function to different variables, they each maintain a different state (data). Because it acts like a factory for manufacturing functions, this is apparently also known as a function factory.

const createCounter = () => {
    let count = 0;
    return function increment() {
        // Continuing to reference the variable `count`
        count = count + 1;
        return count;
    };
};
// countUp and newCountUp are each different increment functions (the inner count variables are also different)
const countUp = createCounter();
const newCountUp = createCounter();
// Since the referenced functions (objects) are different, === does not match
console.log(countUp === newCountUp);// false
// Their respective states are also different
console.log(countUp()); // => 1
console.log(newCountUp()); // => 1

What is the Benefit of Using Closures?

One answer to the title of this section is as follows:

  • You don't have to pollute the global environment

Using closures allows you to prevent global pollution. In other words, it means you can write highly maintainable programs. By using the characteristics of closures, you can reference variables enclosed in a lexical scope, avoiding the definition of unnecessary global variables and keeping the global environment clean.

Summary

  • A closure is a mechanism that allows a function to maintain state by continuing to reference specific variables within it.
  • A closure acts as a function factory that defines a new function every time it is called.
  • Using closures helps prevent global pollution and improves maintainability.

That's all.
If you find any mistakes or have any supplementary information, I would appreciate it if you could let me know in the comments.
Thank you.

References

Functions and Scope
Closures - JavaScript | MDN
Seriously explaining JavaScript closures - I want to automatically generate programs

Discussion