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:
function outerFunction() {
let count = 0;

return function() {
count += 1;
return;
};
};
function outerFunction() {
let count = 0;

return function() {
count += 1;
return;
};
};
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
MarkBoots
MarkBoots3d ago
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
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
yes. unless someone has anything else to add, i think you're spot on
vinicius!
vinicius!OP3d ago
thanks mark
Choo♚𝕂𝕚𝕟𝕘
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.
vinicius!
vinicius!OP3d ago
great addition, thank you choo
Want results from more Discord servers?
Add your server