DEV Community

german9304
german9304

Posted on

2 1

Javascript: Closures 101

A closure is a way to have access to the scope of an outer function.

However according to mozilla:
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

I'll give a better explanation with code:

Example 1

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

let result = count();
console.log(result()); // 1
console.log(result()); // 2

In this example, a variable named count is declared, and this variable belongs to the scope of the outer function, however the anonymous function inside has access to the count variable.

 () => (count = count + 1);

As you can see when the result function is called the count variable increments:

let result = count();
console.log(result()); // 1
console.log(result()); // 2

Example 2

In this example, you would expect the result of index would be 0 ... 10,
however this is not the case, index will always be 10.

for (var index = 0; index < 10; index++) {
  (function closure() {
    setTimeout(() => {
      console.log(`i ${index}`);
    }, 0);
  })();
}

There are two ways to fix this:

Using an enclose variable

for (var index = 0; index < 10; index++) {
  (function closure() {
    var _index = index;
    setTimeout(() => {
      console.log(`i ${_index}`);
    }, 0);
  })();
}

or using let variable

for (let index = 0; index < 10; index++) {
  (function closure() {
    setTimeout(() => {
      console.log(`i ${index}`);
    }, 0);
  })();
}

Thank you for reading the post, if something is not clear please leave a feedback. I could give more explanation of closures or another topic.

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong · web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌶️🔥

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay