Core JavaScript 1.5 Guide:Block Statement
From MDC
[edit] Block Statement
A block statement is used to group statements. The block is delimited by a pair of curly brackets:
{
statement_1
statement_2
.
.
.
statement_n
}
Example
Block statements are commonly used with control flow statements (e.g. if, for, while).
while (x < 10) {
x++;
}
Here, { x++; } is the block statement.
Important: JavaScript does 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;
}
alert(x); // outputs 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 outputted 1.