Nino Filiu
Nino Filiu

Reputation: 18473

Which truthy values have no property?

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
  1. Might throw if x is null or undefined
  2. Would be perfect, but I can't use optional chaining (for some reason out of the scope of this question)
  3. Works & is used by other libraries like lodash and coffeescript to access props in a null safe way, but reads ugly
  4. 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 and undefined, but perhaps there exist an exotic JS value that is both truthy and throws on property access

Upvotes: 0

Views: 176

Answers (1)

CertainPerformance
CertainPerformance

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

Related Questions