Skip to content
Advertisement

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

I am wondering if these two examples are identical.

    // sampler pack one
    const something = '5'
    console.log(typeof something)
    const thing = +(something)
    console.log(typeof thing)
    
    // sampler pack two
    const something2 = '5'
    console.log(typeof something2)
    const thing2 = Number(something2)
    console.log(typeof thing2)

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:

const unaryStart = performance.now()
const something2 = '5'
const thing2 = +(something2)
const unaryEnd = performance.now()
console.log((unaryEnd - unaryStart) + ' ms')

const numberStart = performance.now()
const something = '5'
const thing = Number(something)
const numberEnd = performance.now()
console.log((numberEnd - numberStart) + ' ms')
        
0.0049999999999954525 ms
0.0049999999999954525 ms

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