2

I've been following a course in Treehouse about JavaScript. I'm currently on the parseInt method. In one of their example, this code was shown:

var j = parseInt("012");

saving it and running in Chrome's console resulted to 10 in their example (which is understandable as 012 is 10 in octal), but in my own browser, it resulted to 12. Is it correct or am I doing something wrong?

1
  • Simple solution here. When using parseInt(), ALWAYS pass the desired radix as the second argument. Always. Commented May 12, 2015 at 0:30

2 Answers 2

4

It's not strange - the behavior is actually implementation dependent.

It could parse as octal 012 or decimal 12.

It's always best to specify the radix parameter when using parseInt(), for example parseInt('012', 10).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I actually specify the radix whenever I use parseInt, I was just confused why the tutorial video had a different browser output when I ran the same code.
0

The difference comes from the type of your variable.

A Number 012 is considered octal, so parseInt(012) is 10.

A String "012" is nothing until parsed. By default parseInt will consider a string as a decimal value, hence "012" will be parsed as 12.

parseInt uses the decimal base by default, but you can force it to the octal base if you like:

parseInt("012", 8) === parseInt(12, 8) === 10
parseInt( 012 , 8) === parseInt(8, 10) === 8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.