Block statement
JavaScript supports a compact set of statements, specifically control flow statements, that you can use to incorporate a great deal of interactivity in your application. This chapter provides an overview of these statements.
The JavaScript reference
contains exhaustive details about the statements in this chapter. The semicolon
(;) character is used to separate statements in JavaScript code.
Any JavaScript expression is also a statement. See Expressions and operators for complete information about expressions.
The most basic statement is a block statement, which is used to group statements. The block is delimited by a pair of curly braces:
{
statement1;
statement2;
// …
statementN;
}Example
Block statements are commonly used with control flow statements (if,
for, while).
while (x < 10) {
x++;
}
Here, { x++; } is the block statement.
Note:
var-declared variables are not block-scoped, but 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 outputs 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 output 1.)