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 use parseInt?

I understand that the parseInt returns a number out of a string but in what kind of a situation would this be used? Once you have the number, what would it be used for?

4 Answers

I would do parseInt to make sure I get an actual number, not a string, before I do any calculation with it.

x = "1";
x + 2 // this give you "12" as a string
parseInt(x) + 2 //this give you 3 as a number

text boxes are a good example. Say you have a text box for a user to input their age. What they input would be a string. If you wanted to do any mathematical operations or comparisons on that object like

if (age > 18)

you would first have to use parseInt(age) to be able to use it as a number.

That makes sense. Thank you for the help!

At first I thought why not just use a variable to output what you want, but keeping in mind whether or not you want a string or actual number really helps. Thanks!