Precedence: Logical or vs. Ternary operator

Yes, the || operator has higher precedence than the conditional ?: operator. This means that it is executed first. From the page you link:

Operator precedence determines the order in which operators are evaluated. Operators with higher precedence are evaluated first.

Let’s have a look at all the operations here:

step = step || (start < end) ? 1:-1;

The operator with the highest precedence is the () grouping operation. Here it results in false:

step = step || false ? 1 : -1;

The next highest precedence is the logical OR operator. step is truthy, so it results in step.

step = step ? 1 : -1;

Now we do the ternary operation, which is the only one left. Again, step is truthy, so the first of the options is executed.

step = 1;

Leave a Comment