DEV Community

german9304
german9304

Posted on

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.

Top comments (0)