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 trialCole Atkinson
2,854 PointsRandom number generating code
I might be reading into this too much, but I want to break down the portion of code that generates the random number between two given inputs.
Math.floor(Math.random() * (15 - 10 + 1)) + 10;
generates a random number between 10 and 15. i.e. [random variable] * 6 + 10
. But to me this is mathematically incorrect. According to BEDMAS the addition should come before the subtraction in the brackets, so in theory this actually produces [random variable] * 4 + 10
meaning that 15 would actually never be reached.
Can someone tell me where or if my logic is flawed? Because this is frustrating me! I am moving on to the next videos with this code, but I want to understand how the fundamentals work rather than just typing what's in front of me. Thanks!
[Edit: I've just realized I've posted this question from the wrong video, but I can't find/see how to move it. Sorry it's in the wrong area!]
2 Answers
Jason Anders
Treehouse Moderator 145,860 PointsHey Cole,
Where you are getting tripped up is your perception of BEDMAS. While it is an acronym for the order of operations, the final four are grouped by two. So the order is:
- Brackets
- Exponents
- Division / Multiplication (done left to right)
- Addition / Subtraction (done left to right)
So, the addition and subtraction (and the division and multiplication) are grouped together in one step and are done in order from left to right. If you want a more detailed example, have a look at this post at Math Central.
Hope that clears it up for you. :)
Cole Atkinson
2,854 PointsThanks Jason!
Wow, that's embarrassing. Sorry I guess this was more of a math question than a JS one :D
Perhaps I should be going back to my primary school textbooks first... thanks again!
Jason Anders
Treehouse Moderator 145,860 PointsNo worries.
Jennifer Nordell
Treehouse TeacherI received your request for assistance, but see that Jason Anders has added a brilliant answer. Don't worry about getting tripped up on the math. Many of us that are learning to code do that. Likely as not, we've been working in other capacities that haven't really required the order of operations since middle school
Luckily, one of the primary reasons we even have computers is to do complicated math