An Interest In:
Web News this Week
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To