Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Our volunteers haven't translated this article into ไทย yet. Join us and help get the job done!

A block statement (or compound statement in other languages) is used to group zero or more statements. The block is delimited by a pair of curly brackets.

Syntax

{
  statement_1;
  statement_2;
  ...
  statement_n;
}
statement_1, statement_2, statement_n
Statements grouped within the block statement.

Description

This statement is commonly used with control flow statements (e.g. if...else, for, while). For example:

while (x < 10) {
  x++;
}

Note that the block statement does not end with a semicolon.

The block statement is often called 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. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.

No block scope

Important: Variables declared with var do not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java. For example:

var x = 1;
{
  var x = 2;
}
console.log(x); // logs 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 C or Java, the equivalent code would have outputted 1.

If you want block scoping consider using let.

Specifications

Specification Status Comment
ECMAScript 2017 Draft (ECMA-262)
The definition of 'Block statement' in that specification.
Draft  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Block statement' in that specification.
Standard  
ECMAScript 5.1 (ECMA-262)
The definition of 'Block statement' in that specification.
Standard  
ECMAScript 3rd Edition (ECMA-262)
The definition of 'Block statement' in that specification.
Standard  
ECMAScript 1st Edition (ECMA-262)
The definition of 'Block statement' in that specification.
Standard Initial definition. Implemented in JavaScript 1.0.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See also

Document Tags and Contributors

 Last updated by: OwnageIsMagic,