Consider the following codes
var value = 0;
for (var i=0; i < arguments.length; i++) {
value += +!!arguments[i];
}
What does +!!
really do here? Is it one good programming style in JavaScript?
!!arguments[i]
is a common idiom, which applies the logical negation twice, to convert the expression arguments[i]
to a real boolean value.
For example,
console.log(!!{});
// true
Why we need two logical negations here? Because, it doesn't change the parity of the data. For example,
if the data was originally Truthy, then !Truthy
will become false
and then inverting it again !false
, you will get true
.
if the data was originally Falsy, then !Falsy
will become true
and then inverting it again !true
, you will get false
.
The +
operator at the beginning of +!!arguments[i]
is to make sure to get a Number value out of the boolean, (as !!arguments[i]
is guaranteed to give a boolean).
In JavaScript, when true
is converted to a number you will get 1
, and 0
for false
.
console.log(+true);
// 1
console.log(+false);
// 0
It's not one operator, it's three: +
and then !
twice.
What that does is apply !
to arguments[i]
, which turns truthy values false
or falsy values to true
, and then applies !
to make false
=> true
and vice-versa, and then applies the unary +
to convert the result to a number (true
=> 1
, false
=> 0
).
A falsy value is any value that coerces to false
. The falsy values are 0
, ""
, NaN
, null
, undefined
, and of course, false
. A truthy value is any other value.
So the net result is to add the count of truthy values in arguments
to value
.
Is it one good programming style in JavaScript?
Using !!
to turn something truthy into true
and something falsy into false
is completely normal practice. Using the unary +
to convert something to a number is also completely normal practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With