Skip to content

Commit eed0f22

Browse files
Added documentation on Closures
1 parent e818188 commit eed0f22

1 file changed

Lines changed: 93 additions & 0 deletions

File tree

13_Closures.md

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Episode 10 : Closures in JS
2+
3+
### Important Interview Question
4+
5+
**Closure :** Function bundled together with its lexical environment/scope.
6+
7+
JS is a weird language. You can pass functions as parameters to another function, assign a variable to an entire function, or even return a function.
8+
eg:
9+
10+
```javascript
11+
function x() {
12+
var a = 7;
13+
14+
function y() {
15+
console.log(a);
16+
}
17+
18+
return y; // instead of y();
19+
}
20+
21+
var z = x();
22+
23+
console.log(z); // value of z is entire code of function y.
24+
```
25+
26+
When functions are returned from another function, they still maintain their lexical
27+
scope.
28+
29+
- When y is returned, not only is the function returned but the entire closure (function y + its lexical scope) is returned and put inside z. So when z is used somewhere else in program, it still remembers variable `a` inside x()
30+
- Closure is a very powerful concept of JS, just because this function remembers things even if they are not in their lexical scope
31+
32+
### Some Gottchas:
33+
34+
#### CODE - 01
35+
36+
```javascript
37+
function x() {
38+
var a = 7;
39+
40+
function y() {
41+
console.log(a);
42+
}
43+
44+
a = 100;
45+
46+
return y;
47+
}
48+
49+
var z = x();
50+
z();
51+
```
52+
53+
OUTPUT:
54+
55+
100
56+
57+
#### CODE - 02
58+
59+
```javascript
60+
function w() {
61+
var b = 900;
62+
63+
function x() {
64+
var a = 7;
65+
66+
function y() {
67+
console.log(a, b);
68+
}
69+
70+
y();
71+
}
72+
73+
x();
74+
}
75+
76+
var z = w();
77+
z();
78+
```
79+
80+
OUTPUT:
81+
82+
7 900
83+
84+
### Uses of Closure
85+
86+
- Module Design Pattern,
87+
- Currying,
88+
- Functions like once(fxn that can be run only once),
89+
- memoize,
90+
- maintaining state in async world,
91+
- setTimeout,
92+
- iterators
93+
- ...

0 commit comments

Comments
 (0)