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 Solution

Andrew Zhao
Andrew Zhao
3,267 Points

Can't we just use parseInt() to round instead of using Math.floor() ?

var input = prompt("Please type a number");
var topNumber = parseInt(input);
var randomNumber = Math.floor(Math.random() * topNumber) + 1;
var message = "<p>" + random number + " is a number between 1 and " + topNumber + ".</p>";
document.write(message);

In the above Code, is it not possible to subsitute line 3 with: var randomNumber = parseInt(Math.random() * topNumber) + 1 ?

1 Answer

I tried a bunch of edge cases to see whether I could get parseInt() to fail. I couldn't, so I suppose you could write it that way. However, the other issue is maintainability - especially if someone else needs to read your code and understand your intent. Since parseInt() is designed to parse strings into integers, and Math.floor() is designed to truncate a float to its integer part, I think that using Math.floor() makes your intent clearer.

Andrew Zhao
Andrew Zhao
3,267 Points

Thank you very, very much Nick.

By the way, what is an edge case?

Edge case typically means testing a minimum or maximum input value. In this scenario, I tested values 0 and 0.5 to see whether the outcomes might vary between Math.floor() and parseInt().