Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 28, 2021 03:26 pm GMT

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();
function x() {    var a = 1;    function y() {        console.log(a) //1      }  y();}x();

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 endlet z = x();  // it will contain y function

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 endlet z = x();  // it will contain y functionz() //1

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!


Original Link: https://dev.to/umashankar_s/closures-in-js-1m0b

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To