3

I recently saw some JS of the form:

function f(x) {{ return x + 1; }}

To my amazement, this is syntactically legal and works fine. At first I thought it was C-style anonymous scopes, but it does not introduce a new scope:

function f(x) {{ var y = x + 1; } return y;} // no error

Why does JS accept these superfluous brackets? How are they interpreted/what do they mean?

Wilfred Hughes
  • 26,027
  • 13
  • 120
  • 177
  • That's a misunderstanding of `var`-declared variable scope. – SE_net4 the downvoter May 14 '15 at 09:48
  • 1
    `{ ... }` is a block. JS does _NOT_ have block-level scoping. So basically it does nothing. http://stackoverflow.com/questions/18130025/javascript-curly-braces-with-no-function-or-json – Sergiu Paraschiv May 14 '15 at 09:49
  • 1
    Whoever wrote it with double braces must have been smoking something, cause it does nothing at all, even if it's valid – adeneo May 14 '15 at 09:49
  • 3
    Also see the MDN: [block statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block). – Qantas 94 Heavy May 14 '15 at 09:49
  • @SergiuParaschiv: Technically, when you commented in May that JavaScript didn't have block-level scoping, you were correct. The final ES2015 spec adding block-level scoping (`let`, `const`, `class`) wasn't released until June. Still, though, the writing was etched into the wall even a couple of years ago... :-) – T.J. Crowder Nov 08 '15 at 09:38
  • @T.J.Crowder: completely agree. JS, as implemented right now by some browsers - and "emulated" with transpilers like Babel - , does have block level scoping. – Sergiu Paraschiv Nov 09 '15 at 08:33

1 Answers1

3

{} simply denotes a block, or "group", of code. Unless paired with something like an if statement it simply doesn't do anything useful. Scope for var is determined by functions in Javascript, not blocks.

The new let in ES6 scopes to blocks.

deceze
  • 471,072
  • 76
  • 664
  • 811