简体   繁体   中英

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) 

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

The - operator is performing a type coercion. There is a common Javascript idiom for converting a string to a number type:

const n = +'60'

That makes n equal to 60 numerically, not just in the string form. This is the same deal, only you're using a negative operator which will invert the sign on the value and provide -60 .

Using + or - symbol will coerce its type. So, -'54'+30 will do math and return -24.

But, if you try like this:

-'54'+'30' // -5430

Then it will not type coerce since both '54' and '30' are string. And JavaScript will not force it to do math.

So, to coerce the type there should be different values like string + number can be type coerced where string will be coerced to number.

Useful links for how type coercion works?

For full detail see this chart for type coercion rule.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM