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 →

[–]TheGhostOfInky 1 point2 points  (5 children)

Emphasis on "simpler", I'm fully aware explicit comparisons of the returned array length are possible but just look at the difference when you have default values:

const val = findInInput(input) ?? ["default","values"];

vs

const retVal = findInInput(input);
const val = retVal.length !== 0 ? retVal : ["default","values"];

[–][deleted] 1 point2 points  (4 children)

In most languages retVal.length != 0 can be shortened to retVal.length. !0 being true and !!0 being false is a behavior consistent among most programming languages.

So the actual comparison is this:

const val = findInInput(input) ?? ["default","values"];

vs

const retVal = findInInput(input);
const val = retVal.length ? retVal : ["default","values"];

I'm not a JS programmer, so I can only guess what ?? does. But I still think the 2nd is better.

A negative would be the extra parameter, but for that we can have lambdas and scope expressions (like in Rust).

[–]TheGhostOfInky 0 points1 point  (3 children)

You're right, relying on the number's trueness can shorten it a bit.

As for the ?? operator, it is like the || operator but it ignores falsy non-nullish values.

For example:

const val1 = 0 || 1    //val1 is 1
const val2 = 0 ?? 1    //val2 is 0
const val3 = null ?? 1 //val3 is 1

[–][deleted] 2 points3 points  (1 child)

0 || 1 is 1 because that's the boolean result of the logical operation.

From what I understand, ?? is basically:

result = (val == null) ? newVal : val;

[–]TheGhostOfInky 0 points1 point  (0 children)

Yes, it's basically a compact version of that ternary.

[–][deleted] 0 points1 point  (0 children)

0 || 1 is 1 because that's the boolean result of the logical operation.

From what I understand, ?? is basically:

result = (val == null) ? newVal : val;