2
var a = {};
a + 1 // return "[object Object]1"

I know why this happened. Object toPrimitive happened and after a.toString return [object Object] and merge with number But why when I type code like this

{} + 1 // return 1

Object not converted string?

Also why object toPrimitive hint Number return 0 When object convert to number this is look valueOf function and why valueOf return 0?

Murad Sofiyev
  • 790
  • 1
  • 8
  • 25
  • 1
    [What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?](https://stackoverflow.com/questions/9032856) – adiga Jul 28 '19 at 11:47

2 Answers2

4

First one is an object and you're adding object with number

var a = {};
a + 1 // return "[object Object]1"

Where as second one is just block statement not object

{} + 1 // return 1
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
3

When not in an expression context, {} will be interpreted as an empty block, so

{} + 1

is like

{
  // no statements here
}
+1

where the + is the unary plus operator. The {} here does not denote an object literal, but a block, and the +1 is the final (and only) expression evaluated, so that's what the console will display if you're just typing into the console.

If you are in an expression context, {} + 1 will indeed evaluate to [object Object]1:

console.log(
  {} + 1
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320