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 trialbelen almonacid
8,495 Pointstrouble with the parenthesis
is there any difference between: var random2 = Math.floor(Math.random() * (topNumber2 - bottomNumber)+ 1) + bottomNumber; and var random2 = Math.floor(Math.random() * (topNumber2 - bottomNumber+ 1)) + bottomNumber; ?? the result is the same when i try it... but i wonder, if the Math.random is 0 , top number 5 , bottom number, 3]... the equation would be 0*(5-3+1) = 0? or 0*(5-3)+1 =1?? is that right (i know im missing the +3, thats why either way the total result is going to be ok)? or the parenthesis do not have any functuality? thank you
2 Answers
Samuel Webb
25,370 PointsThe parenthesis are used to establish precedence and to make sure things happen in a specific order. Check out MDN - Operator precedence for more information about how the operators work and what their precedence is.
If Math.random()
were 0, topNumber was 5 and bottomNumber was 3 this is how it would go.
Math.floor(Math.random() * (topNumber2 - bottomNumber+ 1)) + bottomNumber;
Math.floor(0 * (5 - 3 + 1)) + 3;
// This would return 3 because of the order of precedence.
Math.floor(Math.random() * (topNumber2 - bottomNumber)+ 1) + bottomNumber
Math.floor(0 * (5 - 3) + 1) + 3;
// This would return 4 because of the order of precedence.
So without the + 3 at the end of those, the first one would return 0 and the second one would return 1 because the 1 is outside of the parenthesis which makes it last in the order or precedence.
Hopefully I explained this well.
Cheers, Sam
belen almonacid
8,495 Pointsthank you Sam.
So if im looking not to have 0 as an answer or a number that is in between, i would opt for the second option right?
Samuel Webb
25,370 PointsGoing off of the order in my answer, the first one is the one to use if you want to include the low number as a possible answer. The second one is the one to use if you want to exclude the low number as a possible answer. As long as the low number isn't set to 0, the answer will never come out to 0.