That's a block statement. Block statements have multiple purposes, none of which are being used by that code (other than perhaps to group the content together as Shmiddty suggested). (In fact, I'd say in that code they're counter-productive, because for the many people coming to JavaScript from languages where all variable declarations are block-scoped, they create the impression that the variable is scoped to the block, which it isn't.)
Uses it can have:
Scoping let
, const
, and class
If that code were using let
, const
, or class
, the block would scope the resulting identifier because let
, const
, and class
are block-scoped in JavaScript. So this outputs "bar"
:
{
var foo = "bar";
}
console.log(foo);
but this throws a ReferenceError
because foo
is scoped to the block:
{
let foo = "bar";
}
console.log(foo);
Providing a block to break
As Esailija points out, if it were labelled and using break
, the break would exit the block early.
Grouping statements attached to a flow-control statement
The most common use of a block statement is to group together the statements attached to a flow-control statement like if
and for
. In this fairly typical if
:
if (something) {
doThis();
doThat();
}
...the {}
aren't part of the if
(you can write if
without using {}
), they're a block statement attached to the if
.