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?
2 Answers 2
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)
.
-
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.defc0de– defc0de2015年05月13日 00:13:55 +00:00Commented May 13, 2015 at 0:13
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
parseInt()
, ALWAYS pass the desired radix as the second argument. Always.