I wanted to add the elements of an array into another, so I tried this:
[1,2] + [3,4]
It responded with:
"1,23,4"
What is going on?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
+operator is not defined for arrays.What happens is that Javascript converts arrays into strings and concatenates those.
Update
Since this question and consequently my answer is getting a lot of attention I felt it would be useful and relevant to have an overview about how the
+operator behaves in general also.So, here it goes.
Excluding E4X and implementation-specific stuff, Javascript (as of ES5) has 6 built-in data types:
Note that although
typeofsomewhat confusingly returnsobjectfor Null andfunctionfor callable Objects, Null is actually not an Object and strictly speaking, in specification-conforming Javascript implementations all functions are considered to be Objects.That’s right – Javascript has no primitive arrays as such; only instances of an Object called
Arraywith some syntactic sugar to ease the pain.Adding more to the confusion, wrapper entities such as
new Number(5),new Boolean(true)andnew String("abc")are all ofobjecttype, not numbers, booleans or strings as one might expect. Nevertheless for arithmetic operatorsNumberandBooleanbehave as numbers.Easy, huh? With all that out of the way, we can move on to the overview itself.
Different result types of
+by operand types* applies to Chrome13, FF6, Opera11 and IE9. Checking other browsers and versions is left as an exercise for the reader.
Note: As pointed out by CMS, for certain cases of objects such as
Number,Booleanand custom ones the+operator doesn’t necessarily produce a string result. It can vary depending on the implementation of object to primitive conversion. For examplevar o = { valueOf:function () { return 4; } };evaluatingo + 2;produces6, anumber, evaluatingo + '2'produces'42', astring.To see how the overview table was generated visit http://jsfiddle.net/1obxuc7m/