Optional chaining should be written as below
a?.[0]?.b?.[0].prop
javascript - null checking of array using question mark break - Stack Overflow
Is it possible to check for null inline in javascript? - Stack Overflow
One Question Poll: If x === null, what do you expect x?.y to be?
What does the question mark in the context of this expression mean: array?.length
Videos
2020 Answer, It Exists!!!
You can now directly use ?. inline to test for existence. It is called the Optional Chaining Operator, supported by all modern browsers.
If a property exists, it proceeds to the next check, or returns the value. Any failure will immediately short-circuit and return undefined.
const example = {a: ["first", {b:3}, false]}
example?.a // ["first", {b:3}, false]
example?.b // undefined
example?.a?.[0] // "first"
example?.a?.[1]?.a // undefined
example?.a?.[1]?.b // 3
domElement?.parentElement?.children?.[3]?.nextElementSibling
To ensure a default defined value, you can use ??. If you require the first truthy value, you can use ||.
example?.c ?? "c" // "c"
example?.c || "c" // "c"
example?.a?.[2] ?? 2 // false
example?.a?.[2] || 2 // 2
If you do not check a case, the left-side property must exist. If not, it will throw an exception.
example?.First // undefined
example?.First.Second // Uncaught TypeError: Cannot read property 'Second' of undefined
?. Browser Support - 94%, Oct '22
?? Browser Support - 94%
Node Support - v14+
Update 2020
This long-wished feature is now available in JavaScript!
I'll redirect to Gibolt's answer, which covers it well.
Original 2018 answer
There is no "null-safe navigation operator" in Javascript (EcmaScript 5 or 6), like
?.in C#, Angular templates, etc. (also sometimes called Elvis operator, when written?:) , at least yet, unfortunately.You can test for
nulland return some dependent expression in a single line with the ternary operator?:, as already given in other answers :
(use === null to check only for nulls values, and == null to check for null and undefined)
console.log(myVar == null ? myVar.myProp : 'fallBackValue');
in some cases, like yours, when your variable is supposed to hold an
object, you can simply use the fact that any object is truthy whereasnullandundefinedare falsy values :if (myVar) console.log(myVar.myProp) else console.log('fallbackValue')You can test for falsy values by coalescing to boolean with
!!and make this inline :console.log(!!myVar ? myVar.myProp : 'fallbackValue');Be very careful though with this "falsy test", for if your variable is
0,'', orNaN, then it is falsy as well, even though it is not null/undefined.