-1

Try this, open the console:

{} + 1
> 1

And

({}) + 1
> "[object Object]1"`

So what the duck is going on there? What are the extra brackets adding?

Zequez
  • 3,399
  • 2
  • 31
  • 42
  • 1
    I know I've seen this asked several times before, I'll try to find one of the duplicates for you. – Barmar Mar 15 '14 at 02:17
  • Cool, thanks. It's difficult to search for these kind of things. – Zequez Mar 15 '14 at 02:18
  • 2
    Braces represent 2 things in JavaScript -- as an *Expression* they're object literals, as a *Statement* they're [blocks](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block). The parenthesis force them to be an *Expression* and create an `Object`. – Jonathan Lonowski Mar 15 '14 at 02:18

1 Answers1

11
{} + 1

Is being read as "empty code block" + 1

({}) + 1

Is "object" + 1

Take a look at the difference between just {} and ({}), for instance. As far as what a code block is:

{
    // any code here is valid, this is an anonymous block
}

When does { define a code block vs an object? If you're similar with the rules of function statements vs function expressions, I believe they're exactly the same in this case:

  • if the { is at the beginning of a line, it's a code block
  • anywhere else it starts an object
  • Cool! I didn't know you could just use empty blocks in JavaScript, years programming, and TIL. Although they do seem kind of pointless. – Zequez Mar 15 '14 at 02:26
  • @Zequez - You "can't", at least not cross-browser. The break somewhere, though I forget exactly where (my guess is IE). They are (currently) pretty much pointless, but you could theoretically use them for code organization. With ES6, however, they'll allow you to isolate variables to blocks using `let` –  Mar 15 '14 at 02:29
  • A bit of a nit pick, but if `{` is at the beginning of a **statement**, it is a block (see [ECMA-262 section 12.4](http://ecma-international.org/ecma-262/5.1/#sec-12.4)), as you might have several statements on the one line and it might be preceded by white space. Of course blocks can be elsewhere too, but in those cases the meaning is established from the preceding code. – RobG Mar 15 '14 at 03:19
  • Oh, and there is no "function statement", there is only function declaration and function expression ([ECMA-262 section 13](http://ecma-international.org/ecma-262/5.1/#sec-13)). :-) – RobG Mar 15 '14 at 03:28