This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the architecture category.
Last Updated: 2024-11-21
I saw the following code and was surprised that when printX()
was called the
2nd time, it displayed 10. I was under the false impression that a closure
copied the "outer" variables at time of definition and kept a copy.
let x = 5
function printX() {
console.log(x)
}
printX() // 5
x = 10
printX() // 10
My assumption was incorrect. What a closure really does (here and across other
languages, like Go) is act as if the function being defined (printX
here) has
an internal pointer to the stack frame containing all the local variables that
were around when the function was defined (such as x
). It doesn't copy the
variables.
More officially, "The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared." (source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)