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) 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
228,991 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.