0

I was looking at addition peculiarities in javascript and have found an oddity which I cannot explain myself.

Summing up two arrays returns the string of values with the brackets omitted. By extension, empty arrays sum up to an empty string.

[1,2,3] + [4,5,6] === "1,2,34,5,6"
[] + [] === ""

On the other hand, regardless of their contents, objects get crushed into "[object Object]".

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

We can read that as "" + "[object Object]" - so far so good. But wait! Let's sum two objects.

{}+{} !== "[object Object][object Object]"
({}+{}) === "[object Object][object Object]"

const x = {}+{};
x === "[object Object][object Object]"

I need to save the addition result before performing the comparison, either by storing it in a variable or at least wrapping it in parentheses. And finally,

({}+[]) === "[object Object]"

makes sense if we think of it as "[object Object]" + "", but removing parentheses changes the result.

{}+[] === 0
({}+[]) === {}+[]
{}+[] !== ({}+[])

What is the logic behind the results which do not match the "convert to strings, then concatenate" pattern, why does adding parentheses change the result, and why is strict equality operator not symmetric in this case?

Mirac7
  • 1,566
  • 4
  • 26
  • 44

0 Answers0