Q: So, I'm looking into writing a slightly more complex operation with logic operators in an if-else statement. I know I can do parentheses, and I know it's the better way of doing this, but I've gotten curious and so I'm going to ask. If I were to do something like this:
How will that be operated without the use of parentheses? I know there is an order of operations for logic operators, similar to PEMDAS, right?
Which Logic Operator Takes Precedence?
Here's an excellent resource for operator precedence.
In JavaScript, every operator is assigned a number, and higher numbers are executed first. Ties are sometimes executed left-to-right and sometimes right-to-left. The MDN page lists out what does what when.
For example, in math 2 / 5 * 2
would produce 0.2
because the multiplication is performed first. JavaScript, however, would produce 0.8
because both multiplication and division have the exact same precedence and ties are performed left-to-right. Since the division is left of the multiplication, JavaScript would perform the division first.
The same is true for Boolean operators.
Because the &&
operator has a higher precedence than ||
, (B && C)
will be grouped together. That means if A
is true OR if both B AND C
are true, then Do something will execute.
However, knowing this is nifty but readability is by far the most important job of the programmer. Why? Because even if the code doesn't work, someone else can look at it and perhaps help fix it. Using complex Boolean if
statements may work just fine but produces some confusing, unreadable code. Consider something like the following instead:
Ian