Optional chaining is a syntax of JavaScript, useful in checking if left side of expression equals null
or undefined
.
If yes, right side of expression is not executed and undefined
is returned.
Optional chaining can be used to acces value by key, by index or to invoke a function.
Attempt to access field from null
or undefined
without optional chaining will end with an error of type Cannot read property 'x' of undefined/null
const val = {a: {}}; val.a.b.c.d // Cannot read property 'c' of undefined val.a.b?.c.d // undefined val.a.b.c() // Cannot read property 'c' of undefined val.a.b.c?.() // undefined val.a.b[1] // Cannot read property '1' of undefined val.a.b?.[1] // undefined