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

116
Views
How can I stop an object property access chain under certain conditions?
  1. Object A has an array of instances of Object B.
  2. Object A also has a getter method that takes in an index and returns the relevant Object B.
  3. Object B has a set of methods that can be called.

I'm trying to call the object B method using an object chain ( a.getB().method() )like below:

class ObjectB{
  foo(){return 'bar'}
}

class ObjectA{
  constructor(){
    this.list = []
   }
  addB(){this.list.push(new ObjectB)}
  getB(index) { if(index < this.list.length) return this.list[index]}
}

a = new ObjectA();
a.addB();
a.getB(0).foo(); // Works
a.getB(4).foo(); // Returns error, since getB(4) is undefined and has no foo()

I tried different else statements in getB() but I can't stop the script from trying to access 'output'.foo().

I tried a try catch in getB(), but I can't force it to give an error at getB(4). Is there a clean way from me to handle this potential issue without try/catching every instance of the last line?

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

0

Use the optional chaining operator: a.getB(4)?.foo() You can also add it for function calls: a.getB(4)?.foo?.(). This last solution works if getB(4) returns an object that is defined, but has no foo function.

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!