Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the result of adding an Object and an Array in javascript?

I tried this code in the address bar:

javascript: alert({} + [])

The result is: [object Object].

javascript: alert(typeof ({} + []))

The result is: string.

Can somebody explain to me what's going on?

like image 417
MicheleA Avatar asked Jan 23 '11 09:01

MicheleA


People also ask

When we use array and object in JavaScript?

Arrays are best to use when the elements are numbers. objects are best to use when the elements strings (text). 2.

Can you add an array to an object?

An array can be inserted into the object with push() function, below examples illustrate the above approach: Example 1: Javascript.

What happens when you add to an array?

In summary, the addition of arrays causes them to be coerced into strings, which does that by joining the elements of the arrays in a comma-separated string and then string-concatenating the joined strings.

Which JavaScript function is used to add an item to an array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().


2 Answers

The concatenation operator (+) concatenates two string values together. If you give it things that are not string values, then it calls the .toString() method on them first.

In response to the comment below, "Yes it does!"

Object.prototype.toString = function () { return "a"; };
Array.prototype.toString = function () { return "b"; };
var foo = {} + [];
alert(foo); // alerts 'ab'

Without the above modifications to the prototypes, if you have alert({} + []) then you are taking {}.toString() (which is "[Object object]") and [].toString() (which is "" as the array is empty), then concatenating them (which is still "[Object object]"). This is a string and typeof will tell you that it is a string.

like image 85
Quentin Avatar answered Sep 24 '22 16:09

Quentin


It looks like because the + operator is not defined to accept arguments as one [] and one {}, it basically converts both to strings (makes more sense than trying to cast them into numbers) and then applies + as the concatenation operator.

Edit: In response to the changed question, I think they are still being converted into a string first. Here's a session in spidermonkey where I tried it out:

js> x=[]+{}
[object Object]
js> z=x[0]
[
js> x.length
15
js> x=[]+{}
[object Object]
js> x.length
15
js> x[0]
[
js> x[1]
o
js> for (var i=0;i<x.length;i++) {print(x[i]);}
[
o
b
j
e
c
t

O
b
j
e
c
t
]
js> typeof(x)
string
js> print(x)
[object Object]

What is happening is that the result of {}+[] is a string, but not en empty string. Rather it is the string "[object Object]".

like image 28
MAK Avatar answered Sep 23 '22 16:09

MAK