Hacker News new | ask | show | jobs
by cdsanchez 5254 days ago
I don't agree that using the unary plus operator is a best practice for string->number conversions. Best practices should advocate maintainability and clarity - in this case parseFloat is the better choice for obvious reasons. Just be aware that parseFloat and unary + aren't exactly equivalent: parseFloat("10x") === 10, +"10x" === NaN.

And no, JavaScript is not a "non-typed language." AFAIK JavaScript is both dynamically and weakly typed. Being in the latter category does mean that it will implicitly convert values to other types in certain scenarios.

2 comments

Casting with Number is also acceptable.

I don't understand why he would recommend unary as a replacement for casting. It obfuscates the intent of your code, which is especially concerning since this reads like a guide for beginners.

careful

   parseFloat("08") === parseFloat("09") === 0

http://stackoverflow.com/questions/850341
That only applies to parseInt because it tries to guess the radix if one isn't supplied. parseFloat assumes base 10 and doesn't accept a radix argument.
Oh that's neat. Thankyou.
whoops, got out of bed too early