Please read my previous post “Let’s Talk About Scopes Baby…” before you continue on as a proper understanding of Scopes is necessary to grasp the beauty of the closure.
Closures are functions that consist of a function within a function, so an outer function and an inner function. Below is a basic example of a closure function:
Below is what is printed to the console:
to the console. If I call the .toString() method on innerCall this is what is logged :
Essentially the variable innerCall now contains the function that was returned from the outerFunc function, making it invocable. The cool thing is that the variables from outeFunc are still available to innerCall so when it is invoked it has access to it’s own variable and can access the outer functions variables by reference. Below is an example of how this could come in handy :
Pretty straight forward right? I hope this has shed some light on closures and their uses, if you have any questions feel free to comment.