DEV Community

kim-jos
kim-jos

Posted on • Updated on

What are Closures in JS?

What is a closure in JS?

A closure is a function bundled together with its lexical environment. The following is a simple example of a closure.

function outer() {
  var a = 7;
  function inner() {
   console.log(a);
  }
  inner();
}
outer();
Enter fullscreen mode Exit fullscreen mode

image

As you can see closure is possible because of the concept of scope chaining which we have discussed in the previous part of this series. If a certain variable is not found in its local memory then it goes down the call stack to its parent's local memory to find the variable which is closure.

Fun problem!

function outer() {
 for (var i = 1; i <= 5; i++) {
  setTimeout(function () {
   console.log(i)
  }, i * 1000)
 }
}
Enter fullscreen mode Exit fullscreen mode

What do you think is the output of this code?

Most people would think that 1, 2, 3, 4, 5 would be the output of the code above. But, the output is actually 6, 6, 6, 6, 6. The reason the code outputs 5 sixes is because JS continues the for loop without waiting for setTimeout to finish. Once setTimeout is ready to output some value, i is already at 6 which is why is outputs 5 sixes. The simple solution is to use let instead of var because it creates a block scope meaning that a new copy of variable i is used for every loop. But can you think of another way to solve this problem without using let? (Hint: closures)

function outer() {
 for (var i = 1; i <= 5; i++) {
  function useClosure(i) {
   setTimeout(function () {
    console.log(i)
   }, i * 1000)
  }
  useClosure(i);
 }
}
Enter fullscreen mode Exit fullscreen mode

The problem was that we needed to create a new copy of variable i each time the loop was executed. This is possible if you use closures.

Top comments (0)