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
David Padilla
5,255 PointsWhy 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
andren
28,558 PointsAddition does not come before subtraction in PEMDAS.
The PEMDAS order is the following:
- Parentheses
- Exponents
- Multiplication and Division (left-to-right)
- 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.
Alexander Besse
Full Stack JavaScript Techdegree Graduate 35,115 PointsI'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.
Dave StSomeWhere
19,870 PointsIf 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.
David Padilla
5,255 PointsDavid Padilla
5,255 PointsThank you Andren! That makes complete sense! :-)