DISCLAIMER: I've written this blog to share with others what I've understood after going through several blogs, articles, videos, etc. So the following written blog might contain some ideas & language influenced by those.
- A closure is a function bundled together with it's lexical environment.
- In simple words a closure gives you access from an outer function's scope from an inner function.
The following is an example of lexical scoping, where
getName() has 2 local variables
It also has a nested method which is accessing these variables of it's other function.
Lexical Scoping describes how a parser resolves variable names when functions are nested.
Now what happens if we return this nested method and call it from outside?
JS Fiddle Link
It works exactly the same as in previous example.
The catch here is when we return the function, it is returned along with its lexical environment. The lexical environment of the inner function
getFullName consists of any local variables that were in-scope at the time when closure was created.