Javascript Best Practices: parseInt( x, 10 );
January 12th, 2008ParseInt is one of the handiest universal functions in javascript. Even though javascript’s ability to cast most any primitive to any other primitive on the fly is handy to say the least, sometimes we need to explicitly parse a string to make sure we have a legitimate number to work with.
ParseInt does this for us. What most developers don’t realize is that parseInt is base agnostic. While it typically assumes base ten, any base between 2 and 36 can be used and is indicated by the optional second argument.
Why is this a problem you might ask? Because octal numbers can be represented by a leading zero. In practice this can cause some interesting effects in your code.
For example:
var x = "010";
console.log( x );
console.log( x - 0 );
console.log( parseInt( x ) );
console.log( parseInt( x , 10 ) );
Returns:
"010"
10
8
10
Note: “010″ is equivalent to 10 inĀ “x – 0″!


Previous Post
Next Post

Leave a Reply