0

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
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
  • I'd take a closer look at 2. If browser compatibility is the issue, could you integrate Babel into your build process (it should already be present anyway, in a reasonably professional project IMO), and then use optional chaining, and have it transpiled down to ES5/ES2015 for production? (if not, OK, but that's what I'd do) – CertainPerformance Feb 18 '21 at 16:34
  • Nope, that's an issue with babel + jest + istanbul that doesn't handles optional chaining, I mean it could theoretically, but our team collectively decided that this work would be too costly! But yes I would agree if it wasn't for that detail – Nino Filiu Feb 18 '21 at 16:47

1 Answers1

1

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).

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320