When it comes to a bunch of values in a row separated by a bunch of logical and comparison operators, you have to decide which values to evaluate or solve for first.
It’s not always left to right.
Some operators take precedence over the others. That sort of means you have to know what operator you should prioritize first and then what goes next.
For the or operator (||), it has pretty low precedence or priority.
Next (higher up in the food chain) is the and operator (&&).
And then you have the comparison operators like greater than, equal to, etc.
You want to evaluate the highest precedence operators first, then you can evaluate the next lower precedence, and then the next one lower than that, and so on.
One thing to note is how I didn’t mention the not operator (!). That’s because it’s a unary operator. It wouldn’t make any sense to prioritize it in a series of values and operators. It doesn’t do any evaluation or comparisons between 2 different values.
It only changes one value to its opposite!
So here’s the precedence order, with the left being a precedence and the right being the least:
|*, /||+, –||<, ==, etc||&&|||||
By the way, if you see two operators in the same cell, it means they have the same precedence. How do you evaluate them if both of them are on the same expression?
If you see both operators with the same precedence, it’s safe to evaluate them from left to right.
Example 1: How to evaluate binary operator based on precedence
Here’s a series of operators on values:
console.log(1 + 4 == 2 && 5 * 2 < 4); //false
It’s going to take a bit of work in explaining what’s happening here and how it ended up being false. But try and go by the precedence table provided above.
Multiplication has the highest precedence, so you want to evaluate its left and right values first (5 and 2). This makes 10.
The addition is the next highest precedence, so you can evaluate 1 and 4 which ends up being 5.
Next we have the less than operator which evaluates (what is now) 10 to be less than 4. Is that true? False. Again, false converts to 0.
Finally, the last operator is the and operator (&&). So what’s 0 && 0?
What to try another one?
Example 2: How to evaluate multiple binary operators in an expression
console.log(2 + 2 == 4 && 5 * 5 > 24); //true
Let’s evaluate this further.
According to the precedence rule, you want to start with the multiplication first so 5 * 5 is 25.
Then next is the addition sign so 2 + 2 is 4.
After that is the greater than operator which is now if 25 (instead of just 5) > 24, which is true. And true translates to 1.
Then we have to do the equal sign which is now 4 == 4, which is true. And again true translates to true.
Finally, we do the and operator which is 1 && 1, which is true!