I am trying to write the shortest readable code to access the property of a variable that I have no information about, but I want this property access to be safe:
const x = getXSomehow();
const y = x.z; // 1
const y = x?.z; // 2
const y = x != null && x.z; // 3
const y = x && x.z; // 4
- Might throw if
x
isnull
orundefined
- Would be perfect, but I can't use optional chaining (for some reason out of the scope of this question)
- Works & is used by other libraries like lodash and coffeescript to access props in a null safe way, but reads ugly
- I wanna use this, but this would fail if there exist something truthy in JS that doesn't let you access its properties - can this even happen? All I can think of is
null
andundefined
, but perhaps there exist an exotic JS value that is both truthy and throws on property access