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?

Sumner Evans
9,1855 gold badges32 silver badges48 bronze badges
asked May 12, 2015 at 0:14
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).

answered May 12, 2015 at 0:17
1
  • 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. Commented May 13, 2015 at 0:13
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
answered May 12, 2015 at 0:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.