JavaScript obscure syntax

Question:

On the Internet, I came across a function that returned the following value:

return ( A < B ? +1 :
(A > B ? -1 : 0)) * [-1,1][+!!reverse];

What is * [-1,1][+!!reverse] going on here?

What are we multiplying by and what does +!!reverse do ?
Exactly what does + give?

Answer:

[-1,1] – array

[-1,1][0] – take the first member of the array

!!reverse – cast reverse to bool

+reverse – cast reverse to int

those. multiply by one of the array members (-1 or 1) depending on the value of the reverse variable

Scroll to Top