Say I have a string, which value is already a number, e.g. var str = "1234"
Now I want to convert it to number.
I have seen two tricks on the internet so far,
+
: var num = +str
*
: var num = str*1
I want to know which one is better in general.
As I saw from the comment of the accepted answer here: Converting Json Results to a Date, it seems like *1
is best to be avoided. Is this true and what is the reason behind it?
Fewer operations, basically.
The unary plus calls the internal toNumber
method, whereas the multiplication operator calls toNumber
as well, then does a math operation on it.
Why do the extra steps?
http://www.ecma-international.org/ecma-262/6.0/#sec-unary-plus-operator
http://www.ecma-international.org/ecma-262/6.0/#sec-applying-the-mul-operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With