Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Sort of trying out some quirks in javascript:

First I did

console.log("5" + 1);

This prints 51, this is normal right, both number and string have a + operator, but since string is the first variable it will convert 1 to a string.

Now when I did this:

console.log(1 + "5")

I expected output to be 6, as I thought it would convert string to a number. However, the magic output was 15.

Could anyone more experienced in javascript brighten this up for me?

share|improve this question
4  
An addition (even of different types) that follows the commutative law isn't a bad thing in general ;-) –  linqu 11 hours ago
2  
possible duplicate: stackoverflow.com/questions/5961000/… (first one found, I'm sure there are many out there) –  rlemon 11 hours ago
2  
@linqu Expect that it is not commutative because "5" + 1 == "51" != "15" == 1 + "5". –  Bakuriu 7 hours ago

5 Answers 5

up vote -5 down vote accepted

Concatenation also uses + in Javascript.

var result = "String" + number + obj;
// is equivalent to
string result = "String" + number.ToString() + obj.ToString();

However thing is, in C# / .net you could do the same thing, and you will get the same result - System.Console.WriteLine("result is " + 10 + 20);.

In JavaScript (and C# for that matter) strings are immutable. They can never be changed, only replaced with other strings. You're probably aware that combined + "String" doesn't directly modify the combined variable - the operation creates a new string that is the result of concatenating the two strings together, but you must then assign that new string to the combined variable if you want it to be changed.

The argument about using mathematical operators to do string concatenation is arguably an "incorrect" argument, but there's also an argument to be made that using + to do a lot of string concatenation can be very slow.

share|improve this answer
    
"but there's also an argument to be made that using + to do a lot of string concatenation can be very slow." this isn't very true anymore. jsperf.com/string-concat-without-sringbuilder/5 which I got linked from this answer –  rlemon 9 hours ago
8  
How does this even answer the question? –  nhahtdh 8 hours ago

Quoting ECMAScript spec The Addition operator ( + ) section:

  1. If Type(lprim) is String or Type(rprim) is String, then
    Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

So the order doesn't matter here.

share|improve this answer
3  
Why odd? If there is a string, then the result is going to be string as well. Easy to remember. It would be weird if result depended on the order of operands, I think. –  dfsq 11 hours ago
3  
Unfortunately, when an operator can be reused the language designers have to chose a rule for each case. IMO this is better than 2 + "Hello" becoming 2 + the ascii value for "Hello". –  Joshpbarron 11 hours ago
1  
@Joshpbarron: What the heck is "the ASCII value for 'Hello'"?? –  Lightness Races in Orbit 8 hours ago
1  
072 101 108 108 111 @LightnessRacesinOrbit –  Joshpbarron 7 hours ago
1  
@LightnessRacesinOrbit: I'm sure there's a way in PHP to make 2 + "Hello" = 2 + the ascii value for "Hello". Have to look it up. :P –  Krumia 7 hours ago

In both cases the value will be converted to a string. When you add a number to a string or a string to a number, the result is a string.

Simply use parseInt(value) or toString(value) to force the conversion.

share|improve this answer
    
Good answer except no citations! –  Lightness Races in Orbit 8 hours ago

It is decided by the language typing discipline. You can read more about weak type predictability here: http://en.wikipedia.org/wiki/Strong_and_weak_typing#Predictability

share|improve this answer
    
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. –  rickerbh 47 mins ago

console.log(1 + "5") I expected output to be 6, as I thought it would convert string to a number. ...

But then what would you expect if you had written the following?

console.log(1 + " fine day")

or

console.log(1 + " answer(s) to my question")

There can be no assurance as a general rule that a string is convertible to a number. But any number can be converted to a string. That's why the conversion rules are written to move toward a type that is compatible. (In contexts where you as a programmer know that a string can be safely converted to a number, then you can do so explicitly so that the + operation is between two numbers. But that is not true in general for strings.)

In other contexts, this is also why small ints and low precision floats would be converted to large ints or double precision floats when operating on mixed types that the latter types. You can safely convert the limited forms into the larger forms, but you cannot safely go in the other direction in general. A small int can be represented as a big int or a double, but the other direction is not generally a safe conversion.

So conversion rules for operation on mixed types are written as much as is feasible to move toward mutually compatible types that are safe common types. It is left to the programmer to write explicit conversions for the special cases where a more general type can be safely converted to a more limited type.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.