-3

I stumbled upon the "?." syntax in another SO question. Something like this -

console.log(x?.y?.z);

What does it do?

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
Charlie
  • 21,138
  • 10
  • 54
  • 85

1 Answers1

0

This is called Optional Chaining.

It allows to use the property chaining without having to validate properties in each level. It short circuits property evaluation without raising exceptions - thus avoiding the "Cannot read X of undefined" error.

let o = {p: {q: 'foo'}};


try {
  console.log('Trying to access the property x');
  console.log(o.x.y);
}
catch(e) {
  console.log('That was an error');
}


console.log('Trying to access the property x with Optional Chaining');

console.log(o?.x?.y);

Optional chaining more use cases

With function calls

let result = someInterface.customMethod?.();

With expressions

let nestedProp = obj?.['prop' + 'Name'];

With array elements

let arrayItem = arr?.[42];

ECMAScript Draft

Charlie
  • 21,138
  • 10
  • 54
  • 85