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?
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With