Reputation: 18473
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
x
is null
or undefined
null
and undefined
, but perhaps there exist an exotic JS value that is both truthy and throws on property accessUpvotes: 0
Views: 176
Reputation: 370589
this would fail if there exist something truthy in JS that doesn't let you access its properties - can this even happen?
It could, but it'd be pretty strange - like a getter that may throw:
const obj = {
get prop() {
throw new Error();
}
};
console.log(obj.prop);
Or a Proxy with the same sort of thing.
But this same method would result in each method throwing - all of 1, 2, 3, and 4; it's too strange to be worth worrying about in normal code, I think.
If it were me, I'd re-examine (2) to see whether it'd be at all possible to change your build process to integrate optional chaining. Otherwise, you'll have to choose between (3) and (4).
Upvotes: 1