Is there a minimalistic syntax to do the same as x === 0 ? true : !!x
.
The goal of this expression is to avoid the exclusion of zero as falsy and yet make sure other falsy values do are converted to false
.
Asked
Active
Viewed 866 times
1
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator – Teemu Aug 30 '21 at 08:48
-
2How is `??` going to help? – Bravo Aug 30 '21 at 08:50
-
Is it only zero you want to exclude? Not `NaN` or `""`? – JayCodist Aug 30 '21 at 08:51
-
@JayCodist: yes, just zero. @Teemu: I fail to see how `??` helps – Akheloes Aug 30 '21 at 08:52
-
You want to allow *any truthy value* and `0`? Including objects, arrays, strings etc? – deceze Aug 30 '21 at 09:01
-
1What is wrong with your existing code? – Salman A Aug 30 '21 at 09:02
-
@deceze: I want to test a condition where `null` and `undefined` should return a falsy but a zero-value should pass. – Akheloes Aug 30 '21 at 09:04
-
@SalmanA: In short I am correcting a bug, the current code is working I just was curious if it could be made shorter or more efficient since it seemed like the type of expression that could be managed by some peculiar operator. – Akheloes Aug 30 '21 at 09:05
-
So, would `typeof x === 'number'` be an option, or is that too restrictive…? – deceze Aug 30 '21 at 09:15
-
@deceze: this could actually make for a smart refactoring, it does answer the specs and is clean enough ! – Akheloes Aug 30 '21 at 10:20
-
1Ternary operators are already designed to be excessively succinct as to be practically unreadable... you want something *even shorter*? – TylerH Aug 30 '21 at 14:28
-
@TylerH: that a good point, I'll leave it at the current "shortiness", should be fine. – Akheloes Aug 30 '21 at 14:32
3 Answers
3
Basically, you want to allow any number?
typeof x === 'number'

deceze
- 510,633
- 85
- 743
- 889
-
He might want to treat NaN as falsy as well which needs an extra `&&`. – Salman A Aug 30 '21 at 12:47
-
https://stackoverflow.com/questions/68981254/operator-to-account-for-zero-but-not-undefined-null/68981425?noredirect=1#comment121915138_68981254… – deceze Aug 30 '21 at 12:48
-
1FWIW, this solution is technically one character longer than OP's current solution. – TylerH Aug 30 '21 at 14:34
-
This doesn't really do it. The OP wants to test for boolean, with all numbers considered truthy. And this will evaluate to false, if x is a truthy value in another type – JayCodist Aug 31 '21 at 08:49
1
I'm not sure that there's a better solution than what you've got. You could also use !!x || x === 0
though

Ashley
- 449
- 4
- 13
-
3
-
That is true, yeah. I'll amend my answer but there is already a better answer above. – Ashley Aug 30 '21 at 15:54