The problem with replacing parseInt with the unary + operator is that they don't have the same semantics. +"" evaluates to 0, while parseInt("", 10) evaluates to NaN. Tricks like this are fine if you know that it won't matter for your input, but generally speaking you're better off with parseInt and a radix. Yes, it's unnecessarily verbose for the normal case, but it's not that verbose.
A couple of other odd cases: +[] evaluates to 0, while +{} evaluates to NaN (parseInt([], 10) evaluates to NaN). +new Date evaluates to the integer representation of the current Unix timestamp; parseInt(new Date, 10) evaluates to NaN.
This is not unique to Javascript. To a Java programmer this behavior seems natural(octal literals lead with a 0) and not really worthy of a angry blog post.
9 comments
[ 2.9 ms ] story [ 35.2 ms ] threadA couple of other odd cases: +[] evaluates to 0, while +{} evaluates to NaN (parseInt([], 10) evaluates to NaN). +new Date evaluates to the integer representation of the current Unix timestamp; parseInt(new Date, 10) evaluates to NaN.
At least all the different browsers' versions of javascript are consistent about that (right?)
irb(main):002:0> "08".to_i => 8 irb(main):003:0> "08".to_i(8) => 0