Skip to content
Advertisement

Is unary operator +(variable) interpreted the same as Number(variable)?

I am wondering if these two examples are identical.

JavaScript

I often use Number() to ensure some strings get interpretted as numbers, so is the unary plus operator identical under the JavaScript hood? Or is it faster? Or does it highlight any special conditions (particularly around large numbers or special kinds of numbers)?

I just ran this test here which shows them pretty identical:

JavaScript
JavaScript

Advertisement

Answer

Both converts a string to Number, from MDN about unary plus +:

[…] unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.

From the standard ECMA 262 V 6, unary plus:

UnaryExpression : + UnaryExpression

  1. Let expr be the result of evaluating UnaryExpression.
  2. Return ToNumber(GetValue(expr)).

From the standard ECMA 262 V 6, Number needs some more steps, because number could be called as constructor and that is checked in step 4, which needs some time.

  1. If NewTarget is undefined, return n.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement