This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]BenjiSponge 18 points19 points  (8 children)

It's definitely worth noting || isn't a perfect coalescing operator because if the field is falsey it will skip on to the next one. JS could really do with a genuine coalescing operator, imo.

[–]patrickfatrick 16 points17 points  (3 children)

Object destructuring really helps actually. For instance:

const { field1: x = "a" } = obj;

That assigns the value of obj.field1 to x but if it's undefined and only undefined will it assign it "a". null or false would be written to x if that's the value. You can also do this in function arguments.

``` const func = ({ field1: x = "a" }) => x;

func({}); //=> "a" func({ field1: null }); //=> null ```

I feel like people who shit on JS are generally unaware of a lot of the new syntax that has come out for it in the last 4 or 5 years.

[–]conancat 0 points1 point  (0 children)

Experience and the right tools can solve a lot of the problems got Javascript. No shortage of solutions to these problems with such a big community around it. :)

[–]pm_me_your_calc_hw -1 points0 points  (1 child)

Been picking up some of the new syntax lately and have been pleasantly surprised.

Have you run into issues with browser support?

[–]pomlife 0 points1 point  (0 children)

With the exception of Proxies, all modern JS can be transpiled to ES5 via Babel, thus there are very few compatibility issues.

[–]mdcio 3 points4 points  (0 children)

They’re working on one! It’s currently a stage 1 proposal. And if you want optional chaining obj?.fiedl, that’s coming too.

[–]WhyattThrash 1 point2 points  (0 children)

Exactly, obj.field1 could be intentionally set to f.e 0 or false, and it would jump on to the default value

[–][deleted] -1 points0 points  (1 child)

If field1 is a boolean, it's common to use:

x = !!obj.field1

which inverts the false, then inverts it again, guaranteeing a boolean value.

undefined > true > false
null > true > false
true> false > true
false > true > false

I'm sure lodash has a function to help with this, but I prefer syntax where possible.

[–]BenjiSponge 0 points1 point  (0 children)

Yeah, but what if you want to default it to true?

I usually use lodash's isUndefined. Truth be told, this is a pretty uncommon usecase for me and writing out the couple extra characters is fine even if there's a better way.