A block statement is used to group zero or more statements. The block is delimited by a pair of braces ["curly brackets"] and contains a list of zero or more statements and declarations. Statements and declarations grouped within the block statement. The block statement is often called the compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript, especially when used in association with control flow statements like
In addition,
combined with block-scoped declarations like Variables declared with Try it
Syntax
StatementList
Description
if...else
and for
. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.let
, const
, and class
, blocks can prevent temporary variables from polluting the global namespace, just
like IIFEs do.Block scoping rules with var or function declaration in non-strict mode
var
or created by function declarations in non-strict mode do not have block scope. Variables introduced within a block are scoped to the containing function or script, and the
effects of setting them persist beyond the block itself. For example:var x = 1;
{
var x = 2;
}
console.log[x]; // 2
This logs 2 because the var x
statement within the block is in the same scope as the var x
statement before the block.
In non-strict code, function declarations inside blocks behave strangely. Do not use them.
Block scoping rules with let, const, class, or function declaration in strict mode
By contrast,
identifiers declared with let
, const
, and class
do have block scope:
let x = 1;
{
let x = 2;
}
console.log[x]; // 1
The x = 2
is limited in scope to the block in which it
was defined.
The same is true of const
:
const c = 1;
{
const c = 2;
}
console.log[c]; // 1; does not throw SyntaxError
Note that the block-scoped const c = 2
does not throw a SyntaxError: Identifier 'c' has already been declared
because it can be declared uniquely within the block.
In strict mode, function declarations inside blocks are scoped to that block and are hoisted.
"use strict";
{
foo[]; // Logs "foo"
function foo[] {
console.log["foo"];
}
}
foo[]; // ReferenceError: foo is not defined
Examples
Using a block statement as the body of a for loop
A for
loop accepts a single statement as its body.
for [let i = 0; i