Value [-1.1] [+ !! boolean_var]

Can someone explain the purpose of double negating reversevar in the code below?

return function (a,b) {
   var A = key(a), B = key(b);
   return ((A < B) ? -1 :
           (A > B) ? +1 : 0)) * [-1,1][+!!reverse];                  
}

As I understand it, the goal is to select the correct index from the array [-1,1], then to use it in multiplication, but it seems to me that [-1,1][+!!reverse];you can safely replace it with[-1,1][+reverse];

Am I really wrong? What do you get or prevent by double negation reversethere?

I saw the above code on this answer.

+5
source share
4 answers

The simplest answer is probably a counter example:

+undefined //NaN
+!!undefined // 0

[], , , [NaN] , "NaN" , undefined:

[1,-1][+undefined]
[1,-1][NaN]
[1,-1]["NaN"]
undefined
+5

, . , JavaScript- . , :

!!"hello" // true
!!"" // false
!!1 // true
!!some_undefined_var // false
+4

!! . , reverse , .

: +!!"hi". 1, +"hi" - NaN.

+2

, + int.

, : "yes", "no", "", true, false, 0,1,2, undefined

double negation will be "yes" → true "no" → true "" → false true → true false → false undefined → false

then + converts the truths to 1, and falses to 0, so that it can be used as an array index.

+1
source

All Articles