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

Sam Sammut
Sam Sammut
1,616 Points

Why would you use parseInt in this code challenge?

So this is my code, why would you use parseInt in this coding challenge? I've seen it used in several examples in the Q&A section. Thank in advance ?.

var userNum = prompt('Please select a number');
console.log(userNum);
var randomNumber = Math.floor( Math.random() * (userNum)) +1;
alert(randomNumber);

1 Answer

For data validation. Even if the data coming in is a number, it is a good practice to use parseInt() when dealing with external data included into your code. If the input comes from the prompt() then the parseInt() is a must, since all data coming in from prompt() is of string type. Cheers.

Sam Sammut
Sam Sammut
1,616 Points

Thanks so much for clearing this up. I've never programmed with JavaScript before so any explanations I get will be insightful. Cheers again!