I was trying to find a solution for counter(i) function of JS fun practice, and I ended up with this:
function counter(start) {
let count = start;
return {
up() {
return ++count;
},
down() {
return --count;
},
}
}
let obj = counter(10);
let {up, down} = obj;
console.log(up()); // 11
console.log(down()); // 10
console.log(down()); // 9
console.log(up()); // 10
up() nor down() would be able to access count. But when I tried to run the code, it worked!counter function returns the object there should be a link between the object and its Lexical Environment so that up() and down() can access count. Is there anything like that?I know how Lexical Environment works, and I wonder if there is a way for objects to access it. When counter function returns the object there should be a link between the object and its Lexical Environment so that up() and down() can access count. Is there anything like that?
Yes. Javascript supports 3 types of scopes:
Anything within a pair of curly braces ( {...} ) forms a block in Javascript. Block scopes have their own lexical environment. So the object returned from counter() is a block which has reference to counter()'s lexical environment using which it can access the count variable.
The functions up() and down() form a closure and hence can access count even when invoked from global i.e. outside of counter()'s scope.