Order of Operations

Grade 3, page 2 of 11. A one-minute read.

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:

JavaScript
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
PriorityOperators
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.

Watch outThe average mistake

Here's a really common bug. We want the average of three test scores:

JavaScriptHas a bug
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:

JavaScriptFixed
const average = (70 + 80 + 90) / 3;
console.log(average);

It prints

80
TipWhen in doubt, use parentheses

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.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning