View Full Version : Anyone seen this trick before?
mschwartz
29 Sep 2009, 7:34 AM
mschwartz@bytor:~/js$ cat test3.js
var i = '5';
print(i+3);
print(parseInt(i)+3);
print(+i+3);
mschwartz@bytor:~/js$ rhino test3.js
53
8
8
Animal
29 Sep 2009, 7:51 AM
It is Javascript's type coercion
Try adding this which will explain:
console.log(typeof +i);
It's a unary positive operator which is for numbers, so Javascript coerces the operand to be a number.
http://en.wikipedia.org/wiki/Unary_operation
mschwartz
29 Sep 2009, 9:01 AM
I know what it is.
The thing is, if people are doing the parseInt() in client code, the unary operator is shorter making the client scripts fewer bytes.
Animal
29 Sep 2009, 9:31 AM
I guess it's a matter of house coding style really.
Personally, I'd prefer all our in house code to use explicit type conversions at the cost of a few bytes in order to maximize maintainability.
I reckon 90% of software costs is in maintenance.
mmusson
29 Sep 2009, 12:26 PM
One benefit of the unary + conversion is that the parseInt() call above actually has a subtle bug. It isn't safe not to provide the optional second parameter specifying the number base because JavaScript will guess the base instead. This guess will usually be base 10 but certain prefixes will lead to other guesses (0 prefix leads to octal, 0x prefix leads to hexadecimal), and that leads to subtle bugs because the programmer is usually assuming that the conversion is base 10.
The unary + always guesses the base so this might be less unexpected behavior but I bet many people don't realize it does this. Also the unary + doesn't handle octal even though parseInt() does. Doh, unexpected behavior again, hello bugs.
I suppose given the options, parseInt() and always providing the base is the best bet figuring that the least unexpected behavior will lead to the least bugs.
hendricd
29 Sep 2009, 2:16 PM
Nice @mmusson. Indeed, BASE?? assumptions will bite you.
mschwartz
30 Sep 2009, 5:43 AM
There's another trick that every Java programmer has used:
var foo = ''+5;
Powered by vBulletin® Version 4.1.5 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.