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 trialSam Sammut
1,616 PointsWhy 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
Martin Zarate
10,723 PointsFor 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
1,616 PointsSam Sammut
1,616 PointsThanks so much for clearing this up. I've never programmed with JavaScript before so any explanations I get will be insightful. Cheers again!