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

Parsing Numbers From Strings: JavaScript, code wrong?

So I was following the "Parsing Numbers From Strings" by Jim Hoskins and gets "1", but I get "19".

Is this a new browser support thing in a newer version of "JavaScript"?

Thanks.

6 Answers

Jim Hoskins
STAFF
Jim Hoskins
Treehouse Guest Teacher

The reason you might get 12 is that some browsers will interpret it in octal, and some will interpret it in decimal. All browsers are not identical. They are completely different pieces of software that all try to meet the same standard. This situation is ambiguous, so different browsers handle it differently.

Jim Hoskins
STAFF
Jim Hoskins
Treehouse Guest Teacher

Yeah, the short story is, using parseInt without the second argument (the base, 10 usually) leads to unexpected, and apparently inconsistent results.

Always do parseInt("019", 10), not parseInt("019"). Passing the second argument removes any ambiguity.

Does it do this automatically? Because on mine by just doing parseInt("019") I get "19".

Jim Hoskins
STAFF
Jim Hoskins
Treehouse Guest Teacher

Well, specifically 019 is unambiguously a decimal number, since 9 is not a valid octal digit. 017 will be ambiguous, since it could be octal or decimal. Without the base specified you could get correct or incorrect numbers, based entirely on the number input. Since parseInt is usually used to turn some string variable into a number, and not literally written out as parseInt("017"), it's advised to always pass the base of 10 as the second argument.

Okay, sorry if I'm not understanding this correctly. So what your saying is that if the number is not an octal one then it will give you a decimal number, and if it is and octal digit then it will give you an octal one? So if that's right then why does: var j = parseInt("012"); give me "12"?

Thanks so much Mr. Hoskins!