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) Creating Reusable Code with Functions Random Number Challenge Solution

parseInt()? Why doesn't the parseInt() work inside the function?

function randomNumber(num1, num2) { //Why doesn't the parseInt() work inside the function? var number =Math.floor(Math.random() * (parseInt(num1) - parseInt(num2) + 1)) + num2; return number; }

// parseInt() outside the function works even with the parseInt() inside the function

/var upper = parseInt(prompt("what is the larger number")); var lower = parseInt(prompt("what is the smaller number")); console.log(randomNumber(upper, lower));/

//This is the code that will not parse the information in the function

/var upper = prompt("what is the larger number"); var lower = prompt("what is the smaller number"); console.log(randomNumber(upper, lower));/

2 Answers

Steven Parker
Steven Parker
218,832 Points

I tried both samples and they each seem to work. I did notice that the inside-the-function version relies on implicit type coercion for the last part of the formula ("+ num2") where it might be better practice to apply parseInt again to convert it explicitly. But the implicit conversion does work.

If you're still having trouble, it might be helpful to share this as a workspace "snapshot", which would make it possible to exactly replicate the entire environment.

You don't need parseInt because your not getting a number from the user. if you did var userNumber= prompt('type a number'); THEN you would need to parseInt the number so it sees it as a number and not a string . But since you arent asking for a number ... you dont need it . The computer is generating one for you.