Closures and their importance in Javascript
What are Closures?
Functions along with a reference to its lexical environment bundled together are known as closures.
Each and every function in javascript has access to its outer lexical environment, which means it has access to the variables and functions which are present in its parent or parent’s parent. Even when this function is executed in some other scope, not in the scope where it is physically present, it still remembers the reference of its lexical scope.
Let’s have a look at a basic example of closures.

Explanation:
- We have a simple function as outerFunc() and inside outerFunc() we have initialized a variable and also declared another function as innerFunc() and logged the value of the variable which was initialized inside outerFunc() and we invoked both the function.
- On executing the above code, it will first search for count inside the innerFunc() and since it won’t find a value it will then move to its parent scope, and then it will log the value of count i.e. 2.

- If we look at source code in the browser and on putting a debugger on the line where we are logging the value of count, We can see Closure inside the scope and it holding the value of the count and pointing to outerFunc.
- Since we have stopped our program inside innerFunc() which apparently holds a value of outerFunc(), JS forms a closure of the outerFunc() and keeps the values that have dependencies later i.e. count in our case.
Read more: https://tudip.com/blog-post/closures-and-their-importance-in-javascript/