Skip to content

Commit 2b62077

Browse files
feat: add lexical scope
1 parent c6d9315 commit 2b62077

File tree

3 files changed

+52
-9
lines changed

3 files changed

+52
-9
lines changed

34_closure/lexical_scoping.js

-9
This file was deleted.

35_lexical_scope/1_lexical_scope.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Lexical Scope
2+
3+
// Resource
4+
5+
// What
6+
// -> Lexical scope in JavaScript means that the scope of a variable is determined by its position within the source code's lexical structure (the location where the variable is declared or defined).
7+
// -> When a function is defined, it captures its surrounding lexical environment(scope chain) at the time of its creation.
8+
9+
// Why
10+
// -> Clarity and Predictability: Helps developers understand where variables are defined and how they are accessed.
11+
// -> Encapsulation: Enables functions to access variables from their containing scope, promoting modular and maintainable code.
12+
// -> Closure: Facilitates the creation of closures, where inner functions retain access to variables in their lexical scope even after the outer function has finished executing.
13+
14+
// Example
15+
function outerFunction() {
16+
const outerVariable = "value";
17+
18+
function innerFunction() {
19+
console.log(outerVariable);
20+
}
21+
22+
return innerFunction;
23+
}
24+
25+
const variable = outerFunction();
26+
variable();
27+
28+
// Note

35_lexical_scope/example.html

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>Lexical Scope Example</title>
7+
</head>
8+
<body style="background-color: #414141">
9+
<button id="greenButton">Green</button>
10+
<button id="blueButton">Blue</button>
11+
</body>
12+
<script>
13+
function clickHandler(color) {
14+
// document.body.style.backgroundColor = `${color}`;
15+
16+
return function () {
17+
document.body.style.backgroundColor = `${color}`;
18+
};
19+
}
20+
21+
document.getElementById("greenButton").onclick = clickHandler;
22+
document.getElementById("blueButton").onclick = clickHandler;
23+
</script>
24+
</html>

0 commit comments

Comments
 (0)