Hilmi
Hilmi

Reputation: 3441

Objects and arrays addition

Can anyone explain to me how the results of the following was evaluated?

{} + {} // NaN
[] + {} // "[object Object]"
{} + [] // 0
[] + [] // ""

Upvotes: 26

Views: 7556

Answers (4)

xdazz
xdazz

Reputation: 160833

Here is a full explanation of this, check it.

And note {} + {} is NaN if you execute it directly in the console because {} is thought of a block rather than an object.

({}+{}) should be '[object Object][object Object]'

The real result is:

console.log({}+{}) // '[object Object][object Object]'
console.log([]+{}) // '[object Object]'
console.log({}+[]) // '[object Object]'
console.log([]+[]) // ''

Upvotes: 20

Donald Duck
Donald Duck

Reputation: 8882

For {}+{}, the first {} is interpreted as a block, the second {} is interpreted as an empty object and the + is interpreted as a unary plus operator, so {}+{} is equivalent to:

{
    //Empty block, does nothing
}

+{}    //Unary + applied to empty object, which is NaN

Similarly, in {}+[], the {} is interpreted as a block and +[] is interpreted as the unary plus operator applied to an empty array, which gives 0.

For []+{}, the + is interpreted as a string concatenation operator, so both the operands are converted to strings, in this case [] get converted to the empty string ("") and {} gets converted to "[object Object]", then both are concatenated together giving ""+"[object Object]" which is "[object Object]".

Similarly, for []+[], both arrays get converted to the empty string, giving ""+"" which is "".

Upvotes: 3

Genosite
Genosite

Reputation: 359

{} + {} 

you can't make an addition or any operation on two object

[] + {} // "[object Object]"

it's just a concat between a string and a object, you have the same result with alert({});

{} + [] // 0

same

[] + [] // ""

concat of two empty string = empty string.

Upvotes: 0

dan-lee
dan-lee

Reputation: 14492

Adding arrays with any object and its string representation always results in a join

For example:

[1] + [2] // is merged to "12", so [] + [] is an empty string ""

The same equals for your second example

['test'] + {} // "test[object Object]"

So an empty array plus an empty object will just return an [object Object]


For adding to empty objects it's easy too:

Evaluate a simple empty object: {} // results in undefined

And adding two undefined values is NaN because there's no way you can make an addition on them.

Note: The return values depend on the implementation of JavaScript (i.e. in which Browser or Environment)

Also: What is {} + {} in JavaScript?

Upvotes: 3

Related Questions