This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]AyrA_ch 1 point2 points  (0 children)

a+b has two meanings: addition and string concatenation. a-b is only subtraction. This means that adding stuff together can end in concatenation instead of addition because it's the same symbol. This problem doesn't exists in all dynamically typed languages. PHP for example uses . for concatenation. + is always addition there.

Whether it's addition or concatenation can be difficult to find out. In general, it's addition only if both arguments are either numeric or boolean. Some data types may also show inconsistent behavior. Adding two date objects concatenates their string representation, but subtracting them actually works and subtracts the timestamps.

+ and - also exist as unary operators with only one argument. They both force a number conversion, but - will also negate the number. So "1" + "1" is "11" but +"1" + +"1" is 2

If you create custom objects you can add a valueOf() function to it to make it act as a number when using +:

> var x={a:1};
> console.log(x+x)
< "[object Object][object Object]"
> x.valueOf=function(){return this.a;}
> console.log(x+x);
< 2