score:1

Accepted answer

As commenters have indicated, modern JavaScript provides the optional chaining operator (?.), which you can use like this (as long as you're not still trying to support IE):

const
  grandparent = getObject(),
  itemsCount = grandparent?.parent?.child?.prop3?.length,
  oops = grandparent?.parent?.child?.length;
console.log(itemsCount ?? "No such property");
console.log(oops ?? "No such property");


function getObject(){
  return {
    parent: {
      child: {
        prop1: 'alpha',
        prop2: 'beta',
        prop3: [
          { item: { name: 'first', type: 'string' }},
          { item: { name: 'second', type: 'number' }}
        ]
      }
    }
  };
}


Related Query

More Query from same tag