JavaScript Coercion for Fun and Performance

JavaScript has a lot of curious quirks, its unusual coercion rules are one of them. Here are some examples:

1 + '2' //=> "12"
1 - '2' //=> -1
1 / '2' //=> 0.5
3 * '2' //=> 6

In the first case, the 1 is coerced into a string, in all the others, the second operand is coerced into a number. Curious indeed, but what about some of the unary operations?

It turns out that the unary + is actually pretty handy:

+'7'    //=> 7
+'7.5'  //=> 7.5
+'-7.5' //=> -7.5
+'011'  //=> 11
+' 11'  //=> 11

It behaves the same as parseFloat in all of the above cases. The one difference I've found is how they handle numbers with commas:

parseFloat('1,000.00')  //=> 1
+'1,000.00'             //=> NaN

Neither result is really what I would have expected, but the unary + is arguably a bit safer. If you're curious there is a nice annotated version of the ECMAScript 5.1 spec detailing this behavior.

Interestingly enough, it turns out that in most browsers I tested, the unary + is actually faster than parseFloat.
Try it for yourself, you might be surprised.

blog comments powered by Disqus
Monkey Small Crow Small