Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of [-1,1][+!!boolean_var]

Tags:

javascript

Can someone please explain the purpose of double-negating the reverse var in the below code?

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

The way I understand it, the purpose is to pick the proper index from the [-1,1] array to then use it in the multiplication but it seems to me that [-1,1][+!!reverse]; could be safely replaced by [-1,1][+reverse];

Am I wrong? What do you gain or prevent by double-negating reverse there?

I saw the above code on this answer.

like image 969
Icarus Avatar asked Mar 30 '12 20:03

Icarus


People also ask

What is meant in List A [- 1 in python?

[-1] means the last element in a sequence, which in this is case is the list of tuples like (element, count) , order by count descending so the last element is the least common element in the original collection.

What does Arr 1 mean?

arr is a pointer to the first element of the array.So, if we move arr by 1 position it will point the second element. If the array base address is 1000, &arr+1 will be 1000 + (5 * 4) which is 1020. If the array base address is 1000, arr+1 will be 1000 + 4 which is 1004. Example.


3 Answers

The easiest answer is probably a counter-example:

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

since contents of [] are generally converted to strings, [NaN] will attempt to access the property called "NaN" from the array, which does not exist and will return undefined:

[1,-1][+undefined]
[1,-1][NaN]
[1,-1]["NaN"]
undefined
like image 148
Dennis Avatar answered Sep 30 '22 15:09

Dennis


Double negating simply ensures that we have a proper boolean. Since reverse could be anything, double negating it invokes JavaScript's "falsy" conversions. So, for example:

!!"hello" // true
!!"" // false
!!1 // true
!!some_undefined_var // false
like image 45
bhamlin Avatar answered Sep 30 '22 14:09

bhamlin


The !! converts the value to a boolean. This is needed if reverse isn't a boolean to start off with.

Consider: +!!"hi". This is 1, but +"hi" is NaN.

like image 21
Rocket Hazmat Avatar answered Sep 30 '22 13:09

Rocket Hazmat