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
Benjamin Hedgepeth
5,672 PointsIsn't the formula slightly wrong?
Shouldn't the expression be
var number = Math.floor(Math.random() * ((upper - lower) + 1)) + lower;
not
var number = Math.floor(Math.random() * (upper - lower + 1)) + lower;
Without the parentheses around upper and lower the math would violate the order of operations. After all, it is the difference between the range PLUS one. Not (upper - (lower + 1))
2 Answers
Mike Wagner
23,888 PointsIn some ways, you might be right, but since the order of operations only slightly matters in relation to adding and subtracting values, it will still function the same. Personally, I like your more explicit version that defines the upper and lower as a single, related entity. I think it shows a more knowledgeable understanding of what is happening, makes for a cleaner, neater code structure, and makes it easier to refactor or change later down the line, should the need arise.
Tri Pham
18,671 PointsAdding and Subtraction actually has the same precedence (doesn't matter if you add first or subtract first). If there were multiplication (by something other than 1) instead of adding 1, then yeah you'd be right.