+ 1
What's the point of !!! in JS and other languages?
I've just seen pro coder using !!! to negate a variable or condition. I checked it against every possible type I know including null and undefined and result was the same for ! as for !!!. Is there any reason to use !!! in javascript? Does it have any purpose in other languages? Is there even a reason to use !! (double !)? I've seen these in some old projects only, but it seems useless now and linters tend to mark it as obsolete.
4 Respostas
+ 1
Sharak I think there are situations where you want a boolean. Here are the common situations.
1. In a predicate that needs to return a boolean value e.g a predicate for filter or sort
2. When using static type checkers like Flow.
3. Some functions simply require booleans and will mess up without it. e.g many libraries may do this
if (val === true) // do something.
If you pass in a truthy, it will fail.
+ 5
There is no difference in its result. For every value of x, !x = !!!x
But technically, there is a subtle but irrelevant difference.
If x = 6
Then,
!x = !6 = false
!!!x = !!false = !true = false
However, !! is not completely irrelevant. It forces any value to become boolean. It is discouraged in JavaScript because there is already a Boolean wrapper for that purpose.
!! 6 = Boolean(6)
+ 2
!! force the value is tested against to be its boolean counterpart rather than kinda ambiguous truthy and falsy.
so !!! is a negation of that boolean value
0
Ore sorry but I can't see even this "irrelevant difference". It's all about what !x and !!!x returns and it's always the same. Surely x and !!x differ in types and values as !!x is always a boolean, but when used as a condition then there's absolutely no difference. Null, undefined, '' (empty string), 0 (zero) - all evaluate to false (just like !!null, !!undefined, !!0 and !!'') so there's really no point to use !! either. Is that correct?