Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript String Assignment Operators

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"
like image 217
Josh Stodola Avatar asked Nov 17 '09 19:11

Josh Stodola


People also ask

What are the JavaScript assignment operators?

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 .

What is === in JavaScript?

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.


2 Answers

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?

like image 193
Sean Vieira Avatar answered Nov 15 '22 02:11

Sean Vieira


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
like image 37
Goyuix Avatar answered Nov 15 '22 01:11

Goyuix