closures in javascript mdn docs

JavaScript Closures: MDN docs

By Daniel King
AD

Closures are a fundamental concept in JavaScript, enabling the code to maintain access to an outer function's scope, even after the outer function has finished execution. They are one of JavaScript's most powerful features, commonly used in functional programming and indispensable for event handlers and modules.

This guide explores closures in JavaScript, providing an in-depth understanding through practical examples, as per the Mozilla Developer Network (MDN) documentation.

Understanding Closures

Closures allow a function to have access to its own scope, the outer function's scope, and the global scope. To grasp this, let's start with a simple example:

AD
Understanding Closures in JavaScript
Understanding Closures in JavaScript
What are Closures in JavaScript?
What are Closures in JavaScript?
Back to Basics - JavaScript Closures
Back to Basics - JavaScript Closures

A closure forms whenever a function is created, at function creation time.

Function Creation

In the following snippet, two scopes are created: the global scope (window in browsers) and the local scope within the 'makeCounter' function.

Closures - JavaScript | MDN
Closures - JavaScript | MDN
How JavaScript Closure Can Make You Sick?
How JavaScript Closure Can Make You Sick?
How JavaScript closures work under the hood [Dmitry Frank]
How JavaScript closures work under the hood [Dmitry Frank]

function makeCounter() { let count = 0; return function() { // This inner function has access to 'count' return count++; }; }

Using the Counter

Now,每次调用`makeCounter()`时,都会返回一个新的闭包,每个闭包都会记录自己的计数:

AD

const counter1 = makeCounter(); const counter2 = makeCounter(); console.log(counter1()); // 0, counter2 does not influence counter1's count console.log(counter1()); // 1, still incrementing its own count console.log(counter2()); // 0, each closed scope is independent

Javascript Closure tutorial ( Closures Explained )
Javascript Closure tutorial ( Closures Explained )
Here’s What You Have To Know About JavaScript Closuers
Here’s What You Have To Know About JavaScript Closuers
an image of a black screen with the text closure
an image of a black screen with the text closure
Solve common JavaScript problems - Learn web development | MDN
Solve common JavaScript problems - Learn web development | MDN
What Is Closure In Javascript, Javascript Closure Example, How To Use Closures In Javascript, Javascript Closure Explanation, Javascript Practice Questions, Choosing Between Java And Javascript, Javascript Programming Concepts, Recursive Javascript Function, Javascript Apply Call Bind Difference
What Is Closure In Javascript, Javascript Closure Example, How To Use Closures In Javascript, Javascript Closure Explanation, Javascript Practice Questions, Choosing Between Java And Javascript, Javascript Programming Concepts, Recursive Javascript Function, Javascript Apply Call Bind Difference
a piece of paper with some type of text on it and an image of a backpack
a piece of paper with some type of text on it and an image of a backpack

Closures in Loops

Closures often come into play when working with loops. Without closures, inner functions would not be able to pull the correct value from the array to execute the respective handler:

Without Closures

Suppose we need to create a set of buttons with specific IDs and corresponding click event handlers:

AD

for (let i = 0; i < 5; i++) { const btn = document.createElement('button'); btn.innerText = `Button ${i + 1}`; btn.addEventListener('click', function () { console.log('Button', i + 1, 'was clicked.'); // Always logs 6 regardless of clicked button }); document.body.appendChild(btn); }

Post by @im-a-developer · 1 image
Post by @im-a-developer · 1 image

With Closures

To achieve the desired result, wrap the event listener with an immediate invoked function expression (IIFE):

for (let j = 0; j < 5; j++) { const btn = document.createElement('button'); btn.innerText = `Button ${j + 1}`; btn.addEventListener('click', ((k) => () => { console.log('Button', k, 'was clicked.'); })(j + 1)); document.body.appendChild(btn); }

AD

Each button click will now log the correct button number due to closures preserving the variable's value at the time of the IIFE's creation.

Mastering closures is crucial for writing efficient and scalable JavaScript code. Now that you're familiar with this concept, you can delve into more advanced topics like currying, partial application, and Dean Edward's Immediate Functions Invoked for Proper Scoping (IIFE).

Happy coding!

AD