Skip to content

Commit d1f6c16

Browse files
Adding Closure
1 parent 52b9f36 commit d1f6c16

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

readme.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ __Table of Contents__
1818
* [Higher-Order Functions (HOF)](#higher-order-functions-hof)
1919
* [Partial Application](#partial-application)
2020
* [Currying](#currying)
21+
* [Closure](#closure)
2122
* [Auto Currying](#auto-currying)
2223
* [Function Composition](#function-composition)
2324
* [Purity](#purity)
@@ -144,6 +145,35 @@ const add2 = curriedSum(2) // (b) => 2 + b
144145
add2(10) // 12
145146

146147
```
148+
##Closure
149+
150+
A very simplistic definition - A closure is a way of accessing a variable outside its scope.
151+
Formally, a closure is a technique for implementing lexically scopped named binding. It is a way of storing a function with an environment.
152+
153+
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.
154+
ie. they allow referencing a scope after the block in which the variables were declared has finished executing.
155+
156+
157+
```js
158+
function getTicker () {
159+
var tick = 0;
160+
function ticker () {
161+
tick = tick + 1;
162+
return tick;
163+
}
164+
return ticker;
165+
}
166+
var tickTock = getTicker();
167+
tickTock(); //returns 1
168+
tickTock(); //returns 2
169+
```
170+
The function getTimer() returns a function(internally called ticker), lets call it tickTock.
171+
172+
Ideally, when the getTimer finishes execution, its scope, with local variable tick should also not be accessible. But, it returns 1, 2, 3.. on calling tickTock(). This simply means that, somewhere it keeps a track of the variable tick.
173+
174+
Lexical scoping is the reason why it is able to find the value of tick, the private variable of the parent which has finished executing. This value is called a closure. The stack along with the lexical scope of the function is stored and upon re-execution same stack is restored.
175+
176+
147177

148178
## Auto Currying
149179
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

Comments
 (0)