Functions are objects in Javascript. So, we could use functions as objects within other functions.
So, the below is valid -
|
|
We call point a variable prod
to getProductPlus
, and pass arguments.
Then we execute prod()
. In other languages this likely implies that the outer function has been executed and has already lost its variables.
However, Javascript behaves differently. It executes the inner function taking variable values that had been supplied to outer function earlier, and provides back the results.
The inner function “closes over” or works together with outer function, regardless of when it is called. This unique function of functions is called ‘closure’ in Javascript, and is super useful.
Closure works because -
- Javascript remembers the environment in which a closure was created. Inner function is created in the context of and within outer function
- Reference is maintained to the context until the evaluation is complete. Variables retain values until inner function is evaluated
We see currying functions in Javascript in another post - closure makes similar implementations really easy.
|
|
Here, the program remembers the values when we initialize square
and cube
. We can then use the initiated variables as functions to get the final result.
You might have seen by now that closures have some degree of similarity with objects
(as in instances of classes
) and methods of objects that retain data specific to objects.