Skip to content

Commit 257d2f7

Browse files
Added Clousers interview questions and Functions
1 parent 8c1f26b commit 257d2f7

2 files changed

Lines changed: 278 additions & 0 deletions

File tree

15_JS_Interview_closures.md

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
## Important Concept:
2+
3+
- Closures are used in encapsulation and data hiding.
4+
5+
**[without closures]** => in this code, anyone can access count and change it.
6+
7+
```javascript
8+
var count = 0;
9+
10+
function increment() {
11+
count++;
12+
}
13+
```
14+
15+
**[with closures]** => putting everything into a function
16+
17+
```javascript
18+
function counter() {
19+
var count = 0;
20+
21+
function increment() {
22+
count++;
23+
}
24+
}
25+
26+
console.log(count); // this will give referenceError as count can't be accessed.
27+
```
28+
29+
**[increment with function using closure]**
30+
31+
```javascript
32+
function counter() {
33+
var count = 0;
34+
35+
return function increment() {
36+
count++;
37+
38+
console.log(count);
39+
};
40+
}
41+
42+
var counter1 = counter(); //counter fxn has closure with count var.
43+
44+
counter1(); // increments counter
45+
```
46+
47+
Above code is not good and scalable for say, when you plan to implement decrement counter at a later stage.
48+
To address this issue, we use constructors
49+
50+
Adding decrement counter and refactoring code:
51+
52+
```javascript
53+
function Counter() {
54+
//constructor function. Good coding would be to capitalize first letter of Counter fun.
55+
var count = 0;
56+
57+
this.incrementCounter = function () {
58+
//anonymous function
59+
count++;
60+
61+
console.log(count);
62+
};
63+
64+
this.decrementCounter = function () {
65+
count--;
66+
67+
console.log(count);
68+
};
69+
}
70+
71+
var counter1 = new Counter(); // new keyword for Counter fxn
72+
73+
counter1.incrementCounter();
74+
counter1.incrementCounter();
75+
76+
counter1.decrementCounter();
77+
78+
// returns 1 2 1
79+
```
80+
81+
### Disadvantages of closure
82+
83+
- Overconsumption of memory when using closure as everytime as those closed over variables are not garbage collected till program expires. So when creating many closures, more memory is accumulated and this can create memory leaks if not handled.
84+
- **Garbage collector** : Program in JS engine or browser that frees up unused memory. In highlevel languages like C++ or JAVA, garbage collection is left to the programmer, but in JS engine its done implicitly.
85+
86+
```javascript
87+
function a() {
88+
var x = 0;
89+
90+
return function b() {
91+
console.log(x);
92+
};
93+
}
94+
95+
var y = a(); // y is a copy of b()
96+
97+
y();
98+
```
99+
100+
Once `a()` is called, its element `x` should be garbage collected ideally. But fxn `b` has closure over var `x`. So memory of `x` cannot be freed.
101+
102+
Like this if more closures formed, it becomes an issue. To tacke this, JS engines like v8 and Chrome have smart garbage collection mechanisms.
103+
104+
Say we have var `x = 0`, `z = 10` in above code. When console log happens, `x` is printed as `0` but `z` is removed automatically.

16_Functions.md

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
# Episode 14: First class Functions and Anonymous functions
2+
3+
## Function statement OR Function Declaration:
4+
5+
Just our normal function definition
6+
7+
A normal function that we create using naming convention. By this we can do the Hoisting.
8+
9+
```javascript
10+
function a() {
11+
console.log("Function Statement");
12+
}
13+
14+
a();
15+
```
16+
17+
## Function Expression:
18+
19+
Assigning a function to a variable. Function acts like a value
20+
21+
When we assign a function into a variable that is Function Expression. We can not do Hoisting by this because it acts like variable.
22+
23+
```javascript
24+
var b = function () {
25+
console.log("Function Expression");
26+
};
27+
28+
b();
29+
```
30+
31+
**Difference between function statement and function expression is Hoisting**
32+
33+
```javascript
34+
a();
35+
b();
36+
37+
function a() {
38+
console.log("Function Statement");
39+
}
40+
41+
var b = function () {
42+
console.log("Function Expression");
43+
};
44+
```
45+
46+
OUTPUT:
47+
48+
Function Statement
49+
50+
Uncaught TypeError: b is not a function.
51+
52+
- We can put `a();` before `function a()` and it will still work. But putting `b();` before `var b = function()` throws a typeError.
53+
- **Why?** During memory creation phase `a` is created in memory and function assigned to `a`. But `b` is created like a variable `(b:undefined)` and until code reaches the function() part, it is still undefined. So it cannot be called.
54+
55+
## Anonymous Function:
56+
57+
A Function without the name is known as Anonymous Function. It is used in a place where function are treated as value.
58+
59+
```javascript
60+
function(){
61+
62+
}
63+
64+
// As it is similar to function statement and According to ECMA script a function should always have a name
65+
66+
// Therefore, this will result in SyntaxError: Function statements require a function name.
67+
```
68+
69+
- They don't have their own identity. So an anonymous function without code inside it results in an error.
70+
- Anonymous functions are used at places where functions are used as values e.g. the code sample for function expression above.
71+
72+
```javascript
73+
var exp = function () {
74+
console.log("Anonymous Function");
75+
};
76+
77+
exp();
78+
```
79+
80+
## Named Function Expression:
81+
82+
Same as Function Expression but function has a name instead of being anonymous.
83+
84+
The function with a name, in the function expression, is known as Named Function Expression.
85+
86+
```javascript
87+
var b = function xyz() {
88+
console.log("Named Function Expression");
89+
};
90+
91+
b(); // prints "Named Function Expression" properly
92+
93+
xyz(); // Throws Uncaught ReferenceError: xyz is not defined.
94+
```
95+
96+
> Function `xyz` is not created in global scope or outer scope. But it is created as a local variable. That means it can be accessed inside the function. So it can't be called.
97+
98+
## Parameters v/s Arguments
99+
100+
When we create and name a function and put some identifiers/variabels in the parenthesis ( ) following it, that variables are called as Parameters.
101+
102+
Ex:
103+
104+
```javascript
105+
function ab(param1, param2) {
106+
// param1 and param2 are local variables inside this function and we can not access it outside this function.
107+
// labels/identifiers that get the arg values
108+
console.log(param1 + param2);
109+
}
110+
```
111+
112+
When we call this function and pass a variable/value in the parenthesis ( ) _followed by function name_, that is our Arguments.
113+
Ex:
114+
115+
```javascript
116+
ab(arg1, arg2); // arguments - values passed inside function call
117+
```
118+
119+
## First Class Function AKA First Class Citizens
120+
121+
- We can pass functions to another function as an arguments.
122+
- The Ability of use function as value, Can be passed as an Argument, Can be executed inside a closured function and Can be taken as return form.
123+
124+
```javascript
125+
var b = function (param1) {
126+
console.log(param1); // prints " f() {} "
127+
};
128+
129+
b(function () {});
130+
```
131+
132+
**This can also be done:**
133+
134+
```javascript
135+
var b = function (param1) {
136+
console.log(param1);
137+
};
138+
139+
function xyz() {}
140+
141+
b(xyz); // same thing as prev code
142+
```
143+
144+
**We can return a function from a function:**
145+
146+
```javascript
147+
var b = function (param1) {
148+
return function () {
149+
console.log(" F C F ");
150+
};
151+
};
152+
153+
console.log(b());
154+
//Logs the entire fxn within b.
155+
// f () {
156+
// console.log(" F C F ");
157+
// };
158+
```
159+
160+
```javascript
161+
var b = function (param) {
162+
return function xyz() {
163+
console.log(" F C F ");
164+
};
165+
};
166+
167+
console.log(b());
168+
//Logs the entire fxn within b.
169+
// f xyz() {
170+
// console.log(" F C F ");
171+
// };
172+
```
173+
174+
Function are heart of JS. They are called first class citizens or first class functions because they have the ability to be stored in the variables, passed as parameters and arguments. They can also be returned in the function.

0 commit comments

Comments
 (0)