DEV Community

Discussion on: Optional Chaining JavaScript / TypeScript

Collapse
 
pmcgowan profile image
p-mcgowan • Edited

There was a massive issue discussion on the TS repo about the "elvis" operator, or safe null coalescing in js. I don't have the link, but a js implementation went to stage 2 IIRC for this exact thing.

Js needs this, as

x && x.y && x.y.z
or
((x || {}).y || {}).z
are obviously terrible.

You could write a simple function using try catch to do this, or prototype on object as well:

Object.prototype._elvis = function (v) {
      let tmp = this;
      try {
          v.split('.').forEach(i => tmp = tmp[i]);
      } catch (e) {
          return null;
      }
      return tmp;
  }

then

x = { y: { z: 2 } };
x._elvis('y.z');  // => 2
x._elvis('y.z.q.r.t');  // => null

Also note - works for null but not undefined.