Objects and arrays addition

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 "".


Here is a full explanation of this, check it.

And note {} + {} be 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([]+[]) // ''

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?

Tags:

Javascript