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 trialZach Patrick
19,209 PointsIs 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
Treehouse Guest TeacherHello 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.
Dan Oswalt
23,438 PointsYou 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.
Zach Patrick
19,209 PointsThanks!
Gunhoo Yoon
5,027 PointsThat'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.
Zach Patrick
19,209 PointsThanks!
Zach Patrick
19,209 PointsZach Patrick
19,209 PointsThank's Justin! That does help!