2

1.{}+[] gives 0

2.[]+{} gives [object object] I know how 1 and 2 comes but

3.{}+[]+{} gives [object object][object object]

how shouldn't it be 0[object object]?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Mitesh
  • 41
  • 5
  • Where is the code executed? – Felix Kling Mar 25 '19 at 07:17
  • Code is executed in Chrome REPL. – Mitesh Mar 25 '19 at 07:19
  • @mplungjan: I think these are all wrong. https://stackoverflow.com/q/36438034/218196 is the right duplicate. – Felix Kling Mar 25 '19 at 07:24
  • Chrome uses a simple heuristic and evaluates a line that starts with `{` and ends with `}` as an expression. Therefore both `{}` in `{}+[]+{}` are evaluated as objects an object, whereas the `{}` in `{}+[]` is a block. – Felix Kling Mar 25 '19 at 07:25
  • See https://stackoverflow.com/questions/36438034/why-is-no-longer-nan-in-chrome-console . The expression is slightly different, but the reason/answer is the same. – Felix Kling Mar 25 '19 at 07:26
  • Well done @FelixKling - It was a dupe of something and the rest are relevant to show type coercion – mplungjan Mar 25 '19 at 07:31
  • 1
    To be absolutely clear: You will get `0[object object]` in other environments (e.g. Firefox). It's just the Chrome console that interprets `{}+[]+{}` as if you write `({}+[]+{})`. – Felix Kling Mar 25 '19 at 07:34
  • Other related questions: https://stackoverflow.com/q/53712304/218196, https://stackoverflow.com/q/50989247/218196 – Felix Kling Mar 25 '19 at 07:37

1 Answers1

0

When you use console.log, it executes toString - which when using {} + [], gives [object Object].

console.log({} + []);

(Note: simply placing {} + [] into the Developer Tools console gives 0, because toString is not called).

That's why this yields [object Object][object Object]:

console.log({} + [] + {});

Because you're adding an object (formed from {} + []) to another object, and because you're using the + concatenation operator, this forces toString - therefore, you're adding [objectObject] and [object Object], yielding [object Object][object Object].

Note: The above all are on Chrome. In Firefox and potentially others, they work differently, which is why some things in your question are different.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79