-1
var x = "5";
var y = 2;
var z = 5-("1"+2)+"2"+"1";
console.log(z) // -721

How is this possible? Please explain about - operator in javascript

  • Kindly Google it. You will find it in JavaScript Specs. – Ahsan Dec 26 '15 at 05:08
  • It's due to type coercion/conversion. The `-` operator expects its operands to be numbers and converts values of any other type to a number. – Jonathan Lonowski Dec 26 '15 at 05:15
  • 1
    Possible duplicate of [JavaScript string and number conversion](http://stackoverflow.com/questions/971039/javascript-string-and-number-conversion) – Gupta Dec 26 '15 at 05:42

3 Answers3

1

("1"+2) gives you "12" via concatenation.

5-"12" gives you -7 because, as Jonathan pointed out, - expects numbers and casts them as necessary.

Then you concatenate -7+"2"+"1" to give you the string "-721"

It's really just an order of operations problem, with concatenation happening after the arithmetic of 7-"12", except in the case where it is in parenthesis to make the "12" in the first place.

Everything works as expected.

Chris Trudeau
  • 1,427
  • 3
  • 16
  • 20
0

Let's break var var z = 5-("1"+2)+"2"+"1"; down

  1. The elements in the quotes are read as string, which therefore becomes a concatenation as suppose to an addition. Because ("1" + 2) is in brackets, it will have precedence. ("1" + 2) = 12

Now you have 5-12+"2"+"1";. Let's break it down into two parts

5 - 12 AND "2" + "1"

a. 5 - 12 = -7
b. "2" + "1" = "21"

Now you have -7 + "21". Since one is a String, it is a concatenation resulting in "-721"

myselfmiqdad
  • 2,518
  • 2
  • 18
  • 33
0

I would suggested you to read

There are many resources which could answer all of your question.

Community
  • 1
  • 1
Gupta
  • 8,882
  • 4
  • 49
  • 59