Skip to content

Commit 32c4ec9

Browse files
committed
feat: 🎸 added closures example
1 parent 8574122 commit 32c4ec9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

2024 Prep/namaste_js/closures.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* * Closure: function along with it's lexical scope bundled together forms a closure
3+
*
4+
*/
5+
6+
/**
7+
* The function x() returns the inner function y().
8+
We assign the result of x() (which is y()) to the variable closureExample.
9+
We then call closureExample(), which still has access to the variable a due to closure, and it logs 7
10+
*
11+
*/
12+
// function x() {
13+
// var a = 7
14+
// function y() {
15+
// console.log(a)
16+
// }
17+
// return y // Returning the inner function y
18+
// }
19+
20+
// var closureExample = x() // Now closureExample holds the function y
21+
// closureExample() // This will log 7
22+
23+
function outest() {
24+
var c = 90
25+
function outer(b) {
26+
function inner() {
27+
console.log({ a, b, c })
28+
}
29+
30+
// let a = 80
31+
return inner
32+
}
33+
return outer
34+
}
35+
36+
let a = 100 // If the reference of a is not found in the whole lexical scope of parent function then, this value of will be considered and logged
37+
// value of a is not present anywhere then it will be reference error since a is not defined anywhere
38+
39+
const exec = outest()('outerParams')
40+
exec()

0 commit comments

Comments
 (0)