Closures in JavaScript

Closures in JavaScript

The Synonym of closure is: the process of closing something

Functions in JavaScript are considered first-class citizens. This implies functions are nothing but objects and hence the operations that we perform on objects can also be performed on functions

Capture.JPG

In the code snippet above we call the outer function outer("hello") and we hit the statement return the inner function and assign it to variable_1. Now when we invoke the inner function by writing variable_1(), hello gets printed. This is a very strange behaviour because hello was passed into the outer function and as its execution is completed it should be removed from the call stack when we should get an error.

What the JavaScript engine does is it keeps a link to this variable for later use, and stores that link in a special function scoped execution context. Such a function with 'memory' about the environment where it was created is simply known as a Closure.