Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "+!!" do in JavaScript? [duplicate]

Tags:

javascript

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?

like image 835
zangw Avatar asked Dec 24 '22 10:12

zangw


2 Answers

!!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
like image 59
thefourtheye Avatar answered Jan 06 '23 16:01

thefourtheye


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.

like image 38
T.J. Crowder Avatar answered Jan 06 '23 18:01

T.J. Crowder