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

Why not use parseInt with the prompt?

Following the example on the last videos we have the following variable:

var guess = prompt('I am thinking of a number between 1 and 6. What is it?');

Then when we want to evaluate the number stored in the variable guess we need to use a parseInt as the prompt saves a String.

Why not do it like this then?

var guess = parseInt(prompt('I am thinking of a number between 1 and 6. What is it?'));

Is there any scenario where this is not a good idea? Thanks

That would be respecting DRY principle and one wouldn't need to use it multiple times, in every evaluation.

1 Answer

Steven Parker
Steven Parker
243,318 Points

:point_right: You may want to check for string responses first.

Before converting the input to a number, you may want to check for an empty string, or something like "quit" and/or "exit" for special handling. You might also want to respond to certain common errors with more explicit messages.

It's still DRY to separate the functions, as you will have only one prompt and one parseInt even if they are on separate lines.

Great example use case Steven.

Thanks for your time. That means I should perform a form validation prior to that. That's right.

What do you mean by "quit" and "exit"? Would that be the button on the prompt?