+ 12

Can you explain this in Javascript? console.log( "1" - - "2");

I came across this in Javascript: console.log( "1" - - "2"); // output 3 Can someone explain it to me. I can't figure it out. Thanks in advance.

17th Mar 2017, 10:20 PM
Wisdom Abioye
Wisdom Abioye - avatar
2 Réponses
+ 3
i figured it out. The first minus sign, makes a subtraction. The second minus sign, makes the string a negative number (-2). so it is 1 - (-2). by now it's just math logic. - (negative)and -(negative) makes +(positive), that's why it's a positive 3.
17th Mar 2017, 10:37 PM
Welliton Malta
Welliton Malta - avatar
+ 2
It is called type coercion. This is a phenomenon where JavaScript attempts to convert a given value to a format suitable for the operation to be performed. JavaScript recognizes an arithmetic operation here and so tries to convert "1" to a number (which it does successfully, btw). It then recognizes the first subtraction operator. -"2" is a way to cleverly convert to a number. It is in the form +/-variable. For example, +"6" returns the positive integer 6. So, -"2" converts "2" to 2 and prepends the negative sign, returning -2. Thus: "1"--"2" = 1 - (-2) = 1 + 2 (minus times minus is plus) = 3
17th Mar 2017, 10:41 PM
John Afolayan