4

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?

zangw
  • 33,777
  • 15
  • 127
  • 153
  • Not very readable to the untrained eye. One can easily do better, like using a ternary operator – mattecapu Jan 16 '16 at 09:55
  • Related: http://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript. –  Jan 16 '16 at 09:58
  • Actually, the `+` is not needed here, since the addition will coerce the boolean to a number anyway. –  Jan 16 '16 at 10:05

3 Answers3

6

!!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
thefourtheye
  • 206,604
  • 43
  • 412
  • 459
4

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.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • Well, for consistency I suggest you start using "truey" then. –  Jan 16 '16 at 10:14
  • @torazaburo: "truthy" and "falsy" are no more similar than "truthy" and "falsey". It would have to be "truy" and "falsy" or "truey" and "falsey" or "truthy" and "falsehoody". English is anarchic. – T.J. Crowder Jan 16 '16 at 10:15
0

Often !! is used to convert variable to boolean type, and + to number. In this example it is first converted to boolean then to number in this case to 1 or 0. Variable value contains number of truthy parameters passed to function.

Viktor Kukurba
  • 1,324
  • 8
  • 14