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) Making Decisions with Conditional Statements Build a Random Number Guessing Game

Zach Patrick
Zach Patrick
19,209 Points

Is there anything wrong with putting the parseInt() function in the var like this...

Is there anything wrong with putting the parseInt() function in the var like this...

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

rather than constantly repeating it in your code?

Thanks

3 Answers

Justin Horner
STAFF
Justin Horner
Treehouse Guest Teacher

Hello Zach,

While it is certainly possibly to do that technically, I would say that you do want to be mindful of readability over time.

While this is a simple example of nested method calls, too many that end up too long is generally something professional developers avoid. Not always, but in most cases.

Just to give an example: Usually I would see that being broken out this way.

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

The value of each line representing its concern separately becomes even more valuable when you begin error handling where you want to isolate one particular function of work to handle exceptions.

I hope this helps.

Zach Patrick
Zach Patrick
19,209 Points

Thank's Justin! That does help!

You can certainly do it that way, not sure what the exercise you're looking at is doing otherwise, but that's how I'd do it.

Gunhoo Yoon
Gunhoo Yoon
5,027 Points

That's a good way to handle integer input but remember to specify the radix for consistent output. Although, it doesn't default to octal like it's used to (at least it seems to be but could be different for legacy browsers.) just put it there for human readers and your safety.

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

That way you always end up with decimal number or NaN and you can use isNaN() to determine insane inputs.