shole shole - 11 months ago 22
Javascript Question

Why +str is a better than str*1 in JS to convert string to number?

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,

  1. Use the unary
    var num = +str

  2. Use the multiply operator
    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
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?