2020 Answer, It Exists!!!
You can now directly use ?.
(Optional Chaining) inline to safely test for existence. All modern browsers support it.
If a property exists, ?.
proceeds to the next check, or returns the valid 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
// Dynamic properties ?.[]
example?.a?.[0] // "first"
example?.a?.[1]?.a // undefined
example?.a?.[1]?.b // 3
// Functions ?.()
null?.() // undefined
validFunction?.() // result
(() => {return 1})?.() // 1
// DOM Access
domElement?.parentElement?.children?.[3]?.nextElementSibling
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 - 82%, Oct 2020
Node Support - 14+
Mozilla Documentation