0

While going around reading a bit about JavaScript coercion, I came a across this.

[] + {}; // [object Object]
{} + []; // 0

I understand how this works but what I am not able to understand is why does "console.log"ging the above two statements and executing them in REPL results in two different things.

When ran in REPL mode

enter image description here

When ran in browser(Chrome, Firefox) 
console.log([] + {}); // '[object Object]'
console.log({} + []); // '[object Object]'

My initial thought was maybe toString being called on the console.log parameters, but that is definitely not the case. Any ideas?

Nash Vail
  • 848
  • 2
  • 11
  • 27

1 Answers1

1

The statement {} + [] is ambiguous to the JavaScript engine; while humans would read this as "the addition of an empty object and an empty array", the JavaScript engine parses this as:

// {} + []
{};   // empty block statement with implicit semicolon
+ []; // empty array, coerced into the number 0
// = 0

When wrapped in parentheses, such as inside a function, this interpretation is invalid, so the engine falls back to interpreting it as the addition of an object (coerced into a string '[Object]') and an empty array (coerced into a string '')

Frxstrem
  • 38,761
  • 9
  • 79
  • 119