How does this JS line work?

I read the code of a third-party javascript library and had the following line:

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

x1, x2 and minWidth are all numbers

I'm curious about the part (x2 < x1 || -1). How does the comparison operator work?

+4
source share
3 answers

First, let's look at the short circuit. Say you have a line like

var A = B || C;

If Bis truthy , then it Awill be set to B. If this is not so, then it Awill be equal C.

Repeatedly applying this to your situation, if x2 < x1true, the result of this expression will be true. Otherwise, the result will be -1.

, Javascript. , , . true 1.

" x2 >= x1, ".

+5

-, x2 x1, true, return -1. true 1, minWidth * 1 or -1

:

minWidth = 5, x1 = 3, x2 = 2. x2 = 5 * (true OR -1)

reduced: x2 = 5*true= x2 = 5*1

, .

+2

,

if(x2 < x1){
    x2 = x1 - minWidth * 1;
} else {
    x2 = x1 - minwidth * -1;
}

JavaScript true 1. , .

, || , true. , , . .

This is what happens in your example. Since the value of that part of the condition when true is also equivalent to 1, the author saved the step and simply used this value.

0
source

Source: https://habr.com/ru/post/1618637/


All Articles