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 JavaScript Basics (Retired) Working With Numbers The Random Challenge

What happens if the user puts the first number as a number that is smaller than the second?

If the user types the first number as a number that is smaller than the second, it will generate a negative number. For example:

num1 = 10; num2 = 25;

Math.floor(Math.random() * (num1 - num2 +1)) + num1; // 10 - 15 + 1 = -13 + 10 = -3.

so eventually it does Math.random() to a number that is between 0 and -3 and says it is in the range of 10 to 25 for instance.

1 Answer

Hanna Mchatton
Hanna Mchatton
10,279 Points

Math.abs(x); will return a positive value.

let example = Math.abs(Math.floor(Math.random() * (num1 - num2 +1)) + num1;);