Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
Do objects have access to outer Lexical Environment?

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
At the first sight I thought there would be an error because objects don't have Lexical Environment. I thought neither up() nor down() would be able to access count. But when I tried to run the code, it worked!
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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:

  1. Global
  2. Function
  3. Block

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!