Last Updated: February 25, 2016
·
1.67K
· eliperelman

Using parseInt without radix

In legacy JavaScript engines, using the parseInt function without the radix parameter had the possibility of parsing a number as octal instead of decimal:

parseInt( '9' ); // outputs: 9
parseInt( '09' ); // outputs: 0
</code></pre>

To correct this, it was important to specify the radix parameter which informs parseInt which base to parse the value as:

// base 10, or decimal
parseInt( '09', 10 ); // outputs: 9
</code></pre>

With the newer, stricter JavaScript engines that are compliant with ECMAScript 5, the radix parameter was defaulted to be 10, making it possible to not have to specify the radix in every single parseInt call. But with most browser-based JavaScript, it must still operate in a legacy environment. You can overcome this by shimming the functionality in older browsers:

(function () {
    // cache the native parseInt method
    var _parseInt = window.parseInt;

// shim the functionality only on older browsers
if ( _parseInt('09') === 0 ) {
  // overwrite the native function
  window.parseInt = function ( str, radix ) {
    // if a radix isn't specified, use 10
    return _parseInt( str, radix || 10 );
  };
}


})();
</code></pre>

There ya go! Now you can use parseInt everywhere without having to having to specify radix 10.