r/javascript • • Feb 20 '18

Optional Chaining may be coming to JavaScript

https://dev.to/sammyisa/optional-chaining-may-be-coming-to-javascript--4ff0
321 Upvotes

100 comments sorted by

View all comments

18

u/[deleted] Feb 20 '18 edited Feb 20 '18

I need this in my life today. I'd say undefined is the biggest annoyance and probably the only major one remaining I have with Javascript. Currently using lodash get for this purpose.

Edit: wanted to expand why lodash get is not good enough for me. I don't mind using library but lodash get doesn't work with TypeScript well.

1

u/Auride Feb 20 '18

I don't imagine it would be particularly hard to implement a TS equivalent yourself, just for this purpose. At least the array variation is pretty simple:

function get(
  objectToAccess:Object,
  path:Array<string|symbol>,
  defaultValue:any = undefined
):any{
  let objUnshelled = objectToAccess;
  for (const key of path) {
    const nextObj = objUnshelled[key];
    if (nextObj === undefined) {
      return defaultValue;
    } else {
      objUnshelled = nextObj;
    }
  }
  return objUnshelled;
}

The string variants are slightly more complicated, but it probably reduces down to applying String.split() and maybe another parse step or two to handle array indexing.

1

u/[deleted] Feb 20 '18

I'm not sure what your function solves. Lodash has TypeScript definitions. The issue is second parameter being string. So you any use autocompletion and it's prone to errors and refactoring is not available either. You also have to cast type. In short, it sucks compared to proposed native way.