Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use the optional chaining operator for function calls:
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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading