2

What could possibly be going on and what do brackets really mean when they change the object literal in this example

> {}
Object {}
> ({})
Object {}
> {}.toString()
VM7282:1 Uncaught SyntaxError: Unexpected token

but...

> ({}).toString()
[object Object]

?

chrisbajorin
  • 5,993
  • 3
  • 21
  • 34
Exitos
  • 29,230
  • 38
  • 123
  • 178
  • Just tried both {}.toString() and ({}).toString() in node.js. I get [object object] for both. How are you testing this? – Sanjeev May 19 '16 at 16:26
  • 1
    @Sanjeev `{}` is a block statement, and then `.toString()` throws. I think node.js does some nasty conversion to expression under the hood, so that `{}` is treated as an object initializer. – Oriol May 19 '16 at 16:27
  • 1
    Yes testing stuff like this in a developer console adds confusion if you're not quite certain what's going on - it's always better to write some "real" code for such syntax experiments. – Pointy May 19 '16 at 16:29
  • Just tested it in chrome, Firfox, and IE with console.log({}.toString()) and console.log(({}).toString()), and still get the same result. – Sanjeev May 19 '16 at 16:32
  • 2
    @Sanjeev Read [When does JS interpret {} as an empty block instead of an empty object?](http://stackoverflow.com/q/26347326/1529630). You are forcing it to be treated as an expression. – Oriol May 19 '16 at 16:40
  • Very interesting. Thanks @Oriol. – Sanjeev May 19 '16 at 16:49

0 Answers0