You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A closure is a way of accessing a variable outside its scope.
149
+
Formally, a closure is a technique for implementing lexically scopped named binding. It is a way of storing a function with an environment.
150
+
151
+
A closure is a scope which captures local variables of a function for access even after the execution has moved out of the block in which it is defined.
152
+
ie. they allow referencing a scope after the block in which the variables were declared has finished executing.
153
+
154
+
155
+
```js
156
+
constaddTo=x=>y=> x + y;
157
+
var addToFive =addTo(5);
158
+
addToFive(3); //returns 8
159
+
```
160
+
The function ```addTo()``` returns a function(internally called ```add()```), lets store it in a variable called ```addToFive``` with a curried call having parameter 5.
161
+
162
+
Ideally, when the function ```addTo``` finishes execution, its scope, with local variables add, x, y should not be accessible. But, it returns 8 on calling ```addToFive()```. This means that the state of the function ```addTo``` is saved even after the block of code has finished executing, otherwise there is no way of knowing that ```addTo``` was called as ```addTo(5)``` and the value of x was set to 5.
163
+
164
+
Lexical scoping is the reason why it is able to find the values of x and add - the private variables of the parent which has finished executing. This value is called a Closure.
165
+
166
+
The stack along with the lexical scope of the function is stored in form of reference to the parent. This prevents the closure and the underlying variables from being garbage collected(since there is at least one live reference to it).
167
+
168
+
Lambda Vs Closure: A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects.
169
+
170
+
A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure.
171
+
172
+
173
+
__Further reading/Sources__
174
+
*[Lambda Vs Closure](http://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda)
Transforming a function that takes multiple arguments into one that if given less than its correct number of arguments returns a function that takes the rest. When the function gets the correct number of arguments it is then evaluated.
0 commit comments