JavaScript Reference ยท Statements and Declarations
Block and empty statements
Reference for JavaScript block statements and the empty statement: grouping code, block scope for let and const, standalone blocks and the stray-semicolon pitfall.
A block statement is a pair of curly braces containing zero or more statements. It lets you use several statements where the language expects just one, as in if, for and while bodies. It also creates a scope for let, const, class and (in strict mode) function declarations.
The empty statement is a lone semicolon. It does nothing, and exists for places where syntax needs a statement but you have nothing to run.
{
const message = "scoped to this block";
}
for (let i = 0; i < 3; i++); // empty body
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
{
statementList
}
; // empty statement
| Part | Description |
|---|---|
statementList |
Zero or more statements and declarations. Can be empty. |
Usage notes
- Scope.
let,constandclassdeclared inside a block are invisible outside it.varignores blocks and is scoped to the function. - Standalone blocks are occasionally used to limit the lifetime of temporary variables or to group a section of a long function. A helper function is usually clearer.
- Object literal confusion. At the start of a statement,
{begins a block, not an object.{ a: 1 }is a block with a labela. To write an object expression at statement level, wrap it in parentheses. An arrow function that returns an object literal needs the same:() => ({ a: 1 }). - Empty statement pitfalls. A semicolon after
if (...),for (...)orwhile (...)makes the body empty, and the following block always runs. Linters report this (no-extra-semi,no-empty). - Intentional empty bodies should be written with a comment or
{}to show they are deliberate:while (condition()) {}. - Function declarations in blocks behave differently between strict and sloppy mode; avoid them.
- Braces for single statements. Always using braces after
ifandforprevents mistakes when adding a second line later. - No value. Blocks are statements, not expressions; they do not produce a value you can assign.
Browser support
Block statements, block scoping and the empty statement work in every current browser and engine.