4 ms·
Yeah, the safe navigation operator is great, and I really miss it especially when I write JavaScript and have to do something like `foo && foo.bar && foo.bar.ba
by schneidmaster 8y ago
Yeah, the safe navigation operator is great, and I really miss it especially when I write JavaScript and have to do something like `foo && foo.bar && foo.bar.baz` instead (...which isn't even the same since it returns `false` if something is null).
- lobo_tuerto 8y agoJust use lodash for that. Your example would become: // this won't throw an exception if foo is null _.get(foo, 'bar.baz') And you can even set a default value to return if it is: https://lodash.com/docs/4.17.11#get https://lodash.com/docs/4.17.11#get
- freewilly1040 8y agoThe point isn't that it's an unsolvable problem, the point is that you have to resort to clunky syntax or a 3rd party library to do this. And for something as basic as this, there's probably a number of different libraries that solve the same problem a slightly different way.
- hombre_fatal 8y agoYou lose all static analysis with that including Typescript checking/inference.
- benaiah 8y ago> which isn't even the same since it returns `false` if something is null That's not the case AFAIK - checking in both node and FireFox, `true && null` evalutes to `null`, `true && undefined` evaluates to `undefined`, and `true && null && true` again evaluates to `null`. In what scenario does `&&` coerce the returned value to a boolean? EDIT: checked MDN's docs at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... - it seems to indicate that there is no such coercion of falsy values to false.
- schneidmaster 8y agoYeah, you're right, I was misremembering the behaviour of `null && null`. At any rate, still clunkier :)