views:

605

answers:

5

I read this question in some post on SO, so please explain this.

Thanking you.

+13  A: 

The + operator is overloaded in JavaScript to perform concatenation and addition. The way JavaScript determines which operation to carry out is based on the operands. If one of the operands is not of class Number (or the number primitive type), then both will be casted to strings for concatenation.

3 + 3 = 6
3 + '3' = 33
'3' + 3 = 33
(new Object) + 3 = '[object Object]3'

The - operator, however, is only for numbers and thus the operands will always be cast to numbers during the operation.

Delan Azabani
gotta love the way java works and all the fun bugs it causes.
pxl
You trollin'? `java !== javascript` :P
Delan Azabani
woops, meant javascript, typed java.
pxl
+23  A: 

+ is the String concatenation operator so when you do '7' + 4 you're coercing 4 into a string and appending it. There is no such ambiguity with the - operator.

If you want to be unambiguous use parseInt() or parseFloat():

parseInt('7', 10) + 4

Why specify the radix to 10? So '077' isn't parsed as octal.

cletus
Just in case: Use parseInt('7', 10) with the base parameter, so that '077' will not be mistaken as an octal integer.
Residuum
@Residuum excellent point.
cletus
Or... you could use `Number('077')` which somewhat acts like `parseFloat` and always treats strings as base 10.
Delan Azabani
You could also just use `+'7' + 4`
Gordon Tucker
+3  A: 

Because + is for concentration, if you want to add two numbers you should parse them first parseInt() and - sign is for subtraction

c0mrade
+1  A: 

The sign + in Javascript is interpreted as concatenation first then addition, due to the fact that the first part is a string ('7'). Thus the interpreter converts the 2nd part (4) into string and concatenate it.

As for '7' - 4, there is no other meaning other than subtraction, thus subtraction is done.

thephpdeveloper
+16  A: 

The '+' operator is defined for both strings and numbers, so when you apply it to a string and a number, the number will be converted so string, then the strings will be concatenated: '7' + 4 => '7' + '4' => '74' But '-' is only defined for numbers, not strings, so the string '7' will be converted to number: '7' - 4 => 7 - 4 => 3

Andy