What's 2 + 3 * 4?
If you said 20, Buggsy just got you. The answer is 14.
JavaScript follows the same order of operations you learned in school (you might know it as BODMAS or PEMDAS): multiplication and division happen before addition and subtraction. So 3 * 4 happens first (giving 12), and then 2 + 12 gives 14.
If you want the addition to happen first, use parentheses:
console.log(2 + 3 * 4);
console.log((2 + 3) * 4);
console.log(10 - 4 - 3);
console.log(2 ** 3 * 2);
It prints
14 20 3 16
| Priority | Operators |
|---|---|
| 1st (highest) | ( ) parentheses |
| 2nd | ** exponent |
| 3rd | *, /, % |
| 4th (lowest) | +, - |
When operators have the same priority, JavaScript generally works left to right. That's why 10 - 4 - 3 is (10 - 4) - 3, which is 3.
Here's a really common bug. We want the average of three test scores:
const average = 70 + 80 + 90 / 3;
console.log(average);
It prints
180
An average of 180 out of 100? Somebody call the newspapers! The problem is that 90 / 3 happens first. The fix is parentheses:
const average = (70 + 80 + 90) / 3;
console.log(average);
It prints
80
Even when they're not strictly needed, parentheses make your intentions crystal clear to anyone reading the code. (price * quantity) + shipping is easier to read than price * quantity + shipping, even though they give the same result.