Skip to content

Instantly share code, notes, and snippets.

@squarism
Created May 8, 2022 18:11
Show Gist options
  • Save squarism/fbd50e62ca85f09b56f27eb14d29a930 to your computer and use it in GitHub Desktop.
Save squarism/fbd50e62ca85f09b56f27eb14d29a930 to your computer and use it in GitHub Desktop.
Closures vs Scope
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()
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