Skip to content
Advertisement

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?

Advertisement

Answer

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.

Advertisement