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 Solution

Teacher Russell
Teacher Russell
16,873 Points

random.js

I'm going to have to sleep on this one for a day, I guess. I don't see why it was necessary to use parseInt. I thought that was Math.floor's job. I suppose I didn't fully understand the instructions. Part 2 of the assignment will DEFINITELY have to wait until I understand why Dave did what he did in part 1. Here's my silly attempt before watching the solution.

var userNumber = prompt('Enter a number from 1 to 10') var randNum = Math.floor(Math.random() * userNumber) + 1; document.write(randNum);

1 Answer

The function parseInt converts the input string assigned to userNumber to an integer, whereas Math.floor rounds down (may also be called truncates) the decimal number to the nearest integer. Thus parseInt is explicitly converting from string type to integer type and Math.floor is converting from a float type to an integer type. (There should also be a semicolon to separate the two var statements.) (If Math.floor is given an integer, it will simply return the same integer.)

Teacher Russell
Teacher Russell
16,873 Points

I must have lost the semi-colon when I pasted that. It worked, as far as I could tell, when I ran it. I realize what parseInt and Math.floor do. I still couldn't understand why he did what he did, and maybe didn't understand what he was asking for, exactly. I still don't. I'll sleep it off. Maybe tomorrow and another explanation. Thanks!