Closure in JavaScript are the function inside a function that makes a function stately. Moreover, closure in JavaScript is the combination of function bundled together with references with its surrounding which is lexical environment. In other words, closure allows us to give the excess to outer function from inner function.
What is the need of closure?
The use of closure is to create self content functions, self
content code, self content module. And, anything we have self content, then we
have self content state. And when we are having self content state then we are
avoiding global variables.
On the other hand, there is a closures() function that has got another inner function init(). Variable x is initialized to 0 at first right after that init() function is incrementing the x variable defined in closures() function. We also have a reference variable for closures() function. Here in case of closure function we can have a reference that says don't let go the memory variables. So this makes function stately.
Therefore, until and unless we end our reference variable in the use, we are able to use the memory memory variables. Here in the example every time we use reference variable we get the incrementation of the varaible.
No comments:
Post a Comment