Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Brett Mchatton
Brett Mchatton
10,279 Points

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

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