Vinay Kumar

Closures in a nutshell

I would define closure as a function holding local variable and having function as return value. It is possible to return more than one function in closure, but if that is the case then I would recommend using class or something similar to class depending on the programming language. Closures are one of the highlights of functional programming.

Imagine closure as an environment holding scoped variables which can be accessed or manipulated outside of the closure only through the returned function. Let's understand closure with the help of an example. For example purpose I have chosen JavaScript. The concept is similar and can be applied to other programming languages.

From the above example code, var i = increment(0)will set start = 0 and var j = increment(10) will set start = 10. The variables i and j are functions and calling them multiple times will return the current available state of start variable within their respective closure environments.