DEV Community

Aryan Chopra
Aryan Chopra

Posted on

Closures in JavaScript

Closures are equivalent to what grammar is to English. If you don't understand closures, it's like speaking English without understanding grammar.
In JavaScript, closures are created every time a function is created. To understand them better, we first need to understand what is lexical scoping.

const outer = function(number1) {
  const inner = function(number2, number3) {
    let sum = number1+number2+number3;
    console.log(number1" + "number2" + "number3" = " + sum);
  }
  inner(3,5);
}
Enter fullscreen mode Exit fullscreen mode
outer(4);
4 + 3 + 5 = 12
Enter fullscreen mode Exit fullscreen mode

In the snippet above, the code inside the inner function can see the variable/binding number by the outer function. But, the bindings number2 and number3 are not visible in the outer function. Every local scope is also able to see all the local scopes outside it. The inner function is lexically bound by that of the outer function. This is lexical scoping.

Now that we have understood what lexical scopes are, we can move towards understanding what closures are.
Closures are nothing but functions bundled together with their lexical scope.
Let's understand this by an example.

function a(){
  let x = 50;
  function b(){
    console.log(x);
  }
  b();
}
Enter fullscreen mode Exit fullscreen mode

What happens when we execute the function a()?
Yup, the variable x gets declared, and when we call the function b, it looks up to it's lexical environment, finds x, and logs it.

Now, consider the code below:

function a(){
  let x = 50;
  function b(){
    console.log(x);
  }
  return b;
}
let c = a();
console.log(c);
Enter fullscreen mode Exit fullscreen mode
> function b(){
  console.log(x);
}
Enter fullscreen mode Exit fullscreen mode

The function a returns another function b, which we are binding to c.
Now, what happens when we execute the code below?

function a(){
  let x = 50;
  function b(){
    console.log(x);
  }
  return b;
}
let c = a();
//.... More code

c();
Enter fullscreen mode Exit fullscreen mode

Now, closures come into play. Remember, closures are nothing but functions bundled together with their lexical scope. Here, c is a closure which binds to the function b along with b's lexical scope, which contains the variable x. So it can access the variable x anywhere in the code.

This is the magic of JavaScript.

I hope you can figure out what the output will be when c is called.

Top comments (0)