Search code examples
javascriptoperator-precedenceunary-operator

In Javascript Why result of -'54'+30 is -24(type coercion in javascript)


Why I am getting the result of -'54'+30 expresion as -24 however when I tried to remove the (minus)- from expression then It is just concatenation of string and gives 5430 as output.Can anyone explain about how is it working.

console.log(-'54'+30)
console.log('54'+30)


Solution

  • Because unary negation has a higher operator precedance than addition.

    Unary negation also converts its operand to a Number Per ECMA Spec 2017:

    The unary - operator converts its operand to Number type and then negates it. Negating +0 produces -0, and negating -0 produces +0.

    In the case of -'54'+30 the steps are:

    1. Evaluate the unary -
    2. The right hand operand is a String so it is turned into a Number
    3. The + is evaluated
    4. The left hand operand is a Number due to step 2 so the + operation is addition instead of concatenation