Palagpat Coding

Fun with JavaScript, HTML5 game design, and the occasional outbreak of seriousness

Shorthand parseInt() alternative

Tuesday, June 12, 2012

I'm still working on teasing out asset management in a generic way for the next installment of Let's Make a Canvas Library. Hopefully it'll be ready today or tomorrow. Meanwhile, I just discovered a cool little JavaScript trick via's creator, Thomas Fuchs.

JavaScript's type coercion, which automatically converts a group of variables to compatible data types before performing operations like concatenation or addition on them, is pretty well known and occasionally affectionately mocked. So when you've got an argument coming into a function that you're pretty sure is a number, but might actually be a string containing a number, the accepted way to make sure you've got an actual number you can do math with is to pass it through parseInt():

function plusOne(n) {
// returns NaN if n is not a number, returns n+1 otherwise
   return isNaN(n) ? NaN : parseInt(n) + 1;

Pretty straightforward, yes? So then today I read Thomas's blog entry comparing code written in Prototype.js with a new port of the same class to underscore.js, and in comparing the two code blocks, I noticed that he was using an extra plus operator (+) to coerce a variable to its numeric version:

// prototype (older) version:
function(b,o){ return b + parseInt(o) }

// underscore (newer) version:
function(b,o){ return b + +o }

I confess I'd never seen this method before, so I played around with it a bit in my console to see if it was functionally equivalent to parseInt(); it's not, exactly, but it covers the simple case:

var x = '123', y = '45px', z = 'six';

> console.log(parseInt(x))

> console.log(+x)

> console.log(parseInt(y))

> console.log(+y)
NaN    // interesting...

> console.log(parseInt(z))

> console.log(+z)

So, there are two big differences I see: first, parseInt() can handle "dirty" input, i.e. a string that starts with a number but has other non-numeric characters too (like '45px' above), and the prefixed-+ method can't (it just returns NaN). Secondly, parseInt can take an optional radix, so you can convert from, say, octal or hexidecimal. Those two differences mean that this shortcut isn't going to be universally useful, but if you have an execution environment where these limitations are acceptable, go for it.

You have been reading Shorthand parseInt() alternative, part of the random geekery that is Palagpat Coding: the personal blog of Rylee Corradini. If you'd like to leave me feedback, you can usually find me lurking on Twitter, where I intermittently share and comment on similar topics.