Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this JS line work?

I was reading the code of a third party javascript library and it had the following line:

x2 = x1 - minWidth * (x2 < x1 || -1);

x1, x2, and minWidth are all numbers

I am wondering about the (x2 < x1 || -1) part. How does the comparison operator work here?

like image 629
Undefined Variable Avatar asked Mar 14 '23 23:03

Undefined Variable


1 Answers

First, let's look at short-circuiting. Say you have a line like

var A = B || C;

If B is a truthy value then A will be set to B. If it is not, then A will be equal to C.

Re-applying that to your situation, if x2 < x1 is true, the result of that expression will be true. Otherwise, the result will be -1.

Next, we consider how type casting works in Javascript. Anytime you multiply using a given value, that value is coerced to a number. For true, that number is 1.

Ultimately, it means "if x2 >= x1, flip the sign of the min width."

like image 60
Mike Cluck Avatar answered Mar 23 '23 15:03

Mike Cluck