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
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
("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.
Let's break var var z = 5-("1"+2)+"2"+"1";
down
("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"
I would suggested you to read
There are many resources which could answer all of your question.