Skip to content

Commit 67a3a5d

Browse files
committed
Lexical Scoping & Closure
1 parent c39f584 commit 67a3a5d

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Notes/LexicalScopingAndClosure.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Lexical scoping
2+
Lexical scoping (also called static scoping) means that the scope of a variable is determined by its position in the source code. In other words, where a variable is defined determines where it can be accessed.
3+
4+
```Javascript
5+
function outer() {
6+
let x = 10;
7+
8+
function inner() {
9+
console.log(x); // inner can access x because x is defined in the outer scope
10+
}
11+
12+
inner();
13+
}
14+
15+
outer();
16+
```
17+
18+
- Here, inner() can access x because x is in the lexical scope of inner().
19+
- Lexical scope is set when the function is written, not when it is called.
20+
21+
22+
# Closure
23+
A closure is the combination of a function bundled together with references to its surrounding lexical environment. It allows the function to "remember" and access variables from its outer scope, even after that outer function has finished executing. In JavaScript, closures are created automatically whenever a function is created.
24+
25+
```Javascript
26+
function outer() {
27+
let counter = 0;
28+
29+
return function inner() {
30+
counter++;
31+
console.log(counter);
32+
};
33+
}
34+
35+
const increment = outer(); // outer() is called, and inner() is returned
36+
increment(); // 1
37+
increment(); // 2
38+
```
39+
40+
- Even though outer() has finished executing, the returned function inner() retains access to counter due to closure.
41+
- This is because the function inner closed over the counter variable.
42+
43+
## Key Concept
44+
| Concept | Description |
45+
|----------------|--------------------------------------------------------------------|
46+
| Lexical Scope | Determined by where variables/functions are defined. |
47+
| Closure | A function that remembers the environment in which it was created. |

0 commit comments

Comments
 (0)