DEV Community

Cover image for Closures in JS
Umashankar S
Umashankar S

Posted on

Closures in JS

What is Closure ?

  • Before get into the closure, lets have a small discussion on lexical scope.

Lexical Scope:- Lexical scope is the ability for a function scope to access variables from the parent scope. which parent ? (nearest parent).

function x() {
    var a = 1;
    function y() {
        var a=2;
        console.log(a) //2
      }
  y();
}
x();
Enter fullscreen mode Exit fullscreen mode
function x() {
    var a = 1;
    function y() {
        console.log(a) //1
      }
  y();
}
x();
Enter fullscreen mode Exit fullscreen mode

So now, hope we understood the basics of lexical scope.

Then what is closure?

  • A function along with its lexical scope formed a closure.

according to that sentence only, we will write a code. so we can understood it better.

below code is as same as above code with little modifications (logixal scope code)

function x() { //closure start
  var a = 1;
  function y() {
      console.log(a)
    }
  return y;
}             // closure end

let z = x();  // it will contain y function
Enter fullscreen mode Exit fullscreen mode

so z will contain y function.so if we invoke z(). what will be the expected output??

function x() { //closure start
  var a = 1;
  function y() {
      console.log(a)
    }
  return y;
}             // closure end

let z = x();  // it will contain y function
z() //1
Enter fullscreen mode Exit fullscreen mode

Yes the output is 1, in z, not only function will store. along with a function. its lexical scope will also come into the picture.

So, what is closure?
A function along with its lexical scope formed a closure. (Sentence concluded).

That's it, thanks for reading!
Cheers!

Top comments (0)