Created
May 8, 2022 18:11
-
-
Save squarism/fbd50e62ca85f09b56f27eb14d29a930 to your computer and use it in GitHub Desktop.
Closures vs Scope
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
x = 1 | |
// this is not the complete story of closure | |
// this is entirely lexical scope | |
const parentFunction = () => { | |
y = 50 | |
console.log(x += 1) | |
console.log(y += 1) | |
const childFunction = () => { | |
x += 1 | |
y += 1 | |
console.log(`childFunction x: ${x}`) | |
console.log(`childFunction y: ${y}`) | |
} | |
childFunction() | |
} | |
parentFunction() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
x = 1 | |
const parentFunction = () => { | |
y = 50 | |
console.log(x += 1) | |
console.log(y += 1) | |
const childFunction = () => { | |
x += 1 | |
y += 1 | |
console.log(`childFunction x: ${x}`) | |
console.log(`childFunction y: ${y}`) | |
} | |
return childFunction | |
} | |
// this is a better demonstration | |
// x is global, when result is called | |
// x is incremented once | |
// y was set to 50, is not global but can be referenced | |
// the context was "enclosed" at creation time | |
const result = parentFunction() | |
x = 40 | |
result() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment