Optional chaining logic

254 Views Asked by At

I'm not sure I get the logic behind the js implementation of optional chaining.

const a = {b:1}

1 > console.log(a?.c)     => undefined
2 > console.log(a?.c?.d)  => undefined
3 > console.log(a?.c.d)   => Uncaught TypeError: Cannot read property 'd' of undefined

everything make sense so long. Then:

4 > console.log(a?.c?.d.e) => undefined
5 > console.log(a?.c?.d.e.f.g) => undefined

Accessing a property of undefined throws an error (#3), but accessing an arbitrary amout of non existing nested properties after 2 optional chaining doesn't throw errors anymore.

1

There are 1 best solutions below

0
On

The comments on the question answer it correctly. Here's a clarification:

console.log(a.c)     // undefined
console.log(a.c.d)   // Uncaught TypeError: Cannot read property 'd' of undefined
console.log(a.c.d.e)   // Uncaught TypeError: Cannot read property 'd' of undefined
console.log(a.c?.d)  // undefined
console.log(a.c?.d.e) // undefined
console.log(a.c?.d.e.f.g) // undefined

You can see that evaluation always stops at c, since there is no property a.c. When it stops, if you have used the optional chaining operator (?.), it returns undefined, if not, it throws an error.

Note that this is a recent feature. For nodejs it appears in version 14, which is production-ready (LTS) as of 2020/10/27.