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 Numbers The Math Object Random Number Challenge – Solution

Tall Toad
Tall Toad
1,428 Points

Why is console.log() not having an issue showing numbers without the parseInt?

// Collect input from a user

const choosenNumber = prompt("Whats your favourite number?");

// Convert the input to a number const favouriteNumber = (choosenNumber);// I know parseInt should be present before the (chosenNumber). But when I run this workspace on the browser, I'm not getting any errors or Nan.

// Use Math.random() and the user's number to generate a random number

const randomNumber = Math.floor( Math.random() * choosenNumber) + 1;

// Create a message displaying the random number

console.log(${randomNumber} is a number between 1 and ${favouriteNumber}.);

1 Answer

Steven Parker
Steven Parker
216,032 Points

For some operations, JavaScript can tell that a number is needed and it performs type coercion, which is essentially converting the string into a number for you automatically.

But you don't want to rely on this, since there will be other cases where it can't perform this for you. Here's an example where it won't work:

const choosenNumber = prompt("Whats your favourite number?");
const twice = choosenNumber + choosenNumber;
console.log(`${choosenNumber} added to itself is not ${twice}, is it?`);
Tall Toad
Tall Toad
1,428 Points

Thanks for the reply Steven Parker, I'm new to coding. Some parts make sense some don't or eventually do. As a newbie, How does one evaluate if they are doing well or not?

Steven Parker
Steven Parker
216,032 Points

If you generally complete the quizzes and challenges with only occasionally needing to review a lesson, you're doing quite well indeed!