-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
  • 879,024
  • 165
  • 1,615
  • 1,639
Charlie
  • 18,636
  • 7
  • 49
  • 75

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
  • 18,636
  • 7
  • 49
  • 75