4

I was looking through some old downvoted questions, and I came across How to add 2 numbers in jQuery, and I saw that:

$(1)+$(2)="[Object object][Object object]"

So then tried to see what $(1) put out, and it turned out to be [1], and likewise for $(2) and [2].

Normally, when you try to add [1]+[2], it will give you "12", but if you add $(1) and $(2), it gives you "[object Object][object Object]".

What is the explanation for this behavior?

Community
  • 1
  • 1
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64
  • 5
    You can find this interesting: https://www.destroyallsoftware.com/talks/wat – Ivanka Todorova Nov 12 '13 at 14:27
  • 2
    `$(1).toString() === "[object Object]"` – JJJ Nov 12 '13 at 14:32
  • [Blog post](http://www.2ality.com/2012/01/object-plus-object.html) related to that video talk. Also, [related question](http://stackoverflow.com/questions/10376485/problems-with-adding-object-with-array). – ajp15243 Nov 12 '13 at 14:36
  • 2
    That's because $(something) returns a jQuery object. If you did this: $(1)[0]+$(2)[0] you'd get the answer "3"... – Stephen Byrne Nov 12 '13 at 14:37

1 Answers1

5

$(1) might display in your console as [1], but don't be fooled, it's still a jQuery object, not an int in an array.

console.log(Array.isArray($(1)) //false

[object Object] is usually what displays if you convert any object to a string, so that's why it shows up as [object Object] when it's a string.

When you do the addition there, it probably first converts both of these objects to strings (because it doesnt know how to add objects) and then concatenates the strings.

egucciar
  • 2,039
  • 6
  • 23
  • 24