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

Hudson Kim
Hudson Kim
2,965 Points

What is the parse int function and what does it do?

SO what exactly does the parse int do? I looked it up but all the explanation seem to be confusing me even more. Please help me understand. Thanks.

1 Answer

Antti Lylander
Antti Lylander
9,686 Points

It converts a string to a number. It only searches the number in the beginning of the string though. If the first character is not a number, NaN is returned.

You can try different values in the console.

parseInt('15 miles') //returs 15
parseInt('about 15 miles') //returns NaN

input = prompt('give an integer') //try giving it an integer, it will return "3" if you type in 3.
typeof input //try then this in console. it will return "string"

integer = parseInt(input) //this will return 3 (no double quotes, meaning that it is a number, not a string anymore)
typeof integer //this returns "number" so now you know that your value is stored as a number and you are safe doing some math with it. Many math methods do the conversion automatically, but it is not a good practice to count on it.

I guess you have been using it with prompt(). The reason for that is the fact that prompt always returns a string value even if you type a number in the prompt. Hope this clears it a bit. Trying stuff in console always helps me.