javascriptecmascript-nextoptional-chaining

How does the JavaScript optional chaining(?.) operator works?


I was looking into the new JS optional chaining?. operator. It helps us from getting errors like this,

TypeError: Cannot read property ‘x’ of undefined

You can write

const obj = {a: 1};
console.log(obj?.b);

without an error. It will return undefined if there is no property named b in the obj object. Now, this is working for the first level of (.) operators. But if I try something like this,

console.log(obj.b.c.d?.e);

This is throwing an error,

Uncaught TypeError: obj.c is undefined // In firefox it throws obj.b is undefined.

But if I write,

console.log(obj.b?.c.d?.e);

It is returning undefined again. Shouldn't it be returning Uncaught TypeError: obj.b.c is undefined?

Is this some implementation gap or am I missing something here? Thanks in advance.

It is resolved now. @Ifaruki's comment has the proper explanation.

Update:its called "chaining" operator. it moves from left to right. if it sees ?. it checks the left value if its undefined. if yes it returns undefined and stops moving to the right. that means if b is already undefined it wont check the values on the right side


Solution

  • Its called "optional chaining" operator. It moves from left to right. if it sees ?. it checks the left value if its undefined or null. if yes, it returns undefined and stops moving to the right. that means if b is already undefined it wont check the values on the right side