Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Why isn't the (higherVal - lowerVal + 1) in the equation not following the order of operations method PEMDAS?

In PEMDAS, "add" goes before "subtract" when determining the order of operations in a math equation. Why isn't that the case here?

For example, if you run this alert(Math.floor(Math.random() * (higherVal - lowerVal + 1)) + lowerVal), JavaScript will subtract higherVal and lowerVal before adding + 1, why?

3 Answers

Addition does not come before subtraction in PEMDAS.

The PEMDAS order is the following:

  1. Parentheses
  2. Exponents
  3. Multiplication and Division (left-to-right)
  4. Addition and Subtraction (left-to-right)

Addition and Subtraction are grouped together because they are considered to have the same priority, and as such when they are mixed together you are supposed to solve whatever appears first from left-to-right. So 5 - 3 + 1 becomes 5 - 3 then 2 + 1. The same is true for Multiplication and Division. 10 / 2 * 6 becomes 10 / 2 then 5 * 6. That's why inputting 10 / 2 * 6 into a proper calculator results in 30 rather than 0.83.

Thank you Andren! That makes complete sense! :-)

I'm not sure what's going on,

alert(Math.floor(Math.random() * (higherVal - (lowerVal + 1))) + lowerVal)

Try this. I wrapped the lowerVal + 1 in parentheses so that it will recognize to do that first.

If you check the documentation in MDN Docs you see that both addition and subtraction are precedence level 13 and its associativity is left to right.