How come I can use +=
on a string, but I cannot use -=
on it?
For example...
var test = "Test";
var arr = "⇔"
test += arr;
alert(test); // Shows "Test⇔"
test -= arr;
alert(test); // Shows "NaN"
Assignment operators. An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .
The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.
Because the +
operator concatenates strings, but the -
operator only subtracts numbers from each other.
As to the why -- probably because it is difficult to determine what people want to do when they subtract strings from each other.
For example:
"My string is a very string-y string" - "string"
What should this do?
The short answer is - it isn't defined to work with strings.
Longer answer: if you try the subtraction operator on two strings, it will first cast them to numbers and then perform the arithmetic.
"10" - "2" = 8
If you try something that is non-numeric, you get a NaN related error:
"AA" - "A" = NaN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With