DEV Community

Discussion on: Day 8 : Learning JS fundamentals, Part -3

Collapse
 
marzelin profile image
Marc Ziel

In languages that treat functions as first class objects (to put it simply: functions are values) there might be a situation when a function outlives the function call in which it was created.

So we need to make sure that the inner function can refer to local variables of the outer function even if the outer function returned (finished executing) to maintain lexical scope.

This means that environment in which function was created must be preserved somewhere.

And that's what a closure is: a function bundled with its lexical environment.

Collapse
 
gauravshekhawat profile image
Gaurav-Shekhawat

Thanks, as always, spent the entire day trying to learn it then wrote whatever I understood till evening with the intention of continuing from there the next day. But your single comment was more fruitful than me wondering entire day looking at differnet sites.

Collapse
 
gauravshekhawat profile image
Gaurav-Shekhawat

I was just curious, if we pass the function let's say to another function, then is the lexical environment of the function passed with it or it is referred from the original parent function every time.

Collapse
 
marzelin profile image
Marc Ziel

Every JS function is a closure so it has its lexical environment "attached" internally.

You can think of it as a special, internal property [[Scope]] on a function that it uses whenever it needs to access external variables.

It's quite similar to object [[Prototype]] used to look up for properties whenever they can't be found on an object itself but unlike [[Scope]] you can access [[Prototype]] with __proto__ or Object.getPrototypeOf() so it can be easier to understand.

Both of them might look magical at first but they're just chains of connected structures looked up in order from closest to farthest in search for properties/variables.

Thread Thread
 
gauravshekhawat profile image
Gaurav-Shekhawat

oh, thanks!!
your comment always motivates me to dig much deeper into the topic

Thread Thread
 
marzelin profile image
Marc Ziel

You're welcome.