Closures works only because of lexical scope and scope chain?
i’m studying this fundamentals concepts of Javascript and i’m a bit confused. I thought closures was a features on its own, but what is actually happening is that a inner function keeps access of the scope of its parent function because of lexical scope and scope chain
Example:
Because of lexical scope, the anonymous function will always have access to the scope of outerFunction, right?
and because of scope chain, when this code execute, javascript will first look at the scope of the inner function looking for the declaration of the variable count.
As it won’t find it there, he’ll them look it up in the parent scope. In the example above he’ll find it in the parent scope, but in a case where he didn’t find anything, he would keep climbing the hierarchy until the global scope and them throw a referenceError if don’t find at all
So, lexical scope allows for a inner function access its parent scope whenever it wants bcs “remembers” that it was declared inside that scope
and scope chain allows the inner function to use variables up in the scope hierarchy
and those behaviors it’s what we call closures
Is it right?
Correct me if i’ve understood that wrong
4 Replies
yes. unless someone has anything else to add, i think you're spot on
thanks mark
An extra detail not in your explanation is that Javascript is a garbage collected language. If there is no valid reference to a value, that value gets discarded. In most functions, the parameters and any variables declared inside that function will be discarded when that function finishes execution. If that function returns another function that has references to either the parameters or variables declared in the outer function, that inner function continues to hold references to these values, so they do not get discarded even after the outer function has finished execution.
great addition, thank you choo