DEV Community

kim-jos
kim-jos

Posted on • Edited on

2 2

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay