0

I have been looking for a way to access a nested level object property without getting a Cannot read property 'xxx' of undefined error.

I also want to easily default values that might not exist.

Theo
  • 1,584
  • 1
  • 17
  • 39

1 Answers1

0

The only way I have come across anything like that is this:

var someObject = {};
var myVar = someObject?.that?.might?.or?.mightnot?.have?.this?.property ?? 'default';

if (someObject?.that?.might?.or?.mightnot?.have?.this?.property === 'some-check') {
    // this throws no error
}

console.log(myVar);
Theo
  • 1,584
  • 1
  • 17
  • 39