3
eo2875
3y

obj &&
obj.property1 &&
obj.property1.property2 &&
obj.property1.property2.property3

OR

(((obj || {}).property1 || {}).property 2 || {}).property3

It's mostly for projects that don't support Webpack 5 optional chaining (like Vue 2).
I prefer the second one since it's shorter

Comments
  • 2
    Why not this

    obj?.property1?.property2?.property3
  • 1
    @rusty-python

    TDLR: Webpack 5 supports it, but Webpack 4 doesn't, and some packages are incompatible with Webpack 5.

    Yes I love that idea. BUT

    Webpack uses the Acorn parses. Webpack 4.X uses Acorn 6.4 (or lower), but Acorn only started supporting optional chaining since >7.3, which is used by Webpack 5. I've tried using Vue 2 with Webpack 5, but it doesn't work
  • 5
    I usually go with the first one (&&), since it has an early exit the first key that doesn’t exist whereas the second walks down every key since the right hand side of every key check is an empty object, which might have the next key in the chain.
  • 5
    I find the first one more readable
  • 0
    Like @AmyShackles said, the first has better performance
  • 1
    @AmyShackles @bioDan Is the difference THAT big? They're both O(1). If I have it on a loop then maybe, but otherwise I think it's as exaggerated as discussing the performance of different implementations of noop.
  • 1
    @eo2875 you must consider the worst case for optimization. And even its in a function without a loop, can you guarantee that in the future the call to that function wont be in a loop?
  • 0
    @eo2875 I do ?s with webpack 4, wtf?
  • 1
    What about something like that:

    export const hasProperty = (obj, path) => {
    let p = path.split('.');
    let o;
    for(let i = 0; i < p.length; i++){
    o = obj[p[i]];
    if(!o)
    return false;
    }
    return true;
    }

    hasProperty(obj, 'property1.property2.property3');
  • 0
    @hack oh yeah I could start a framework called Properly
  • 1
    @eo2875 why if you used typescript? Pretty sure this can be just enabled with that parser, no?
  • 1
    @rusty-python I did try. Now that I'm testing more it seems to be a problem only inside templates, not in scripts. Idk what the parser is for Vue templates
Add Comment