Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 *1 is best to be avoided. Is this true and what is the reason behind it?

like image 506
shole Avatar asked Apr 28 '16 03:04

shole


1 Answers

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

like image 149
Jeremy J Starcher Avatar answered Oct 14 '22 11:10

Jeremy J Starcher