I was answering a question on quora and encountered something like following:
// if(true)
{
var qq = 1;
}
Immediately I fired up chrome and
It is a block.
Syntactically, a block is just a bunch of statements that are grouped together.
Block : { StatementList }
StatementList
: StatementListItem
| StatementList StatementListItem
StatementListItem
: Statement
| Declaration
But here's the tricky part: blocks are statements, too.
Statement : BlockStatement
BlockStatement : Block
And there you have it, now you can define compound statements such as if
or while
in terms of an abstract Statement
, without having to worry about whether it is a single statement or a block.
IfStatement
: if ( Expression ) Statement else Statement
| if ( Expression ) Statement
IterationStatement
: while ( Expression ) Statement
| for ( LeftHandSideExpression in Expression ) Statement
| for ( LeftHandSideExpression of AssignmentExpression ) Statement
Isn't it beautiful?
As a side effect of this language design, blocks can contain other blocks inside — it isn't worth prohibiting this quirk explicitly in the language specification, although semantically in EcmaScript 5.1 inner blocks were indeed superfluous and very rarely used.
{
var x = 1;
{
var x = 2; // The same variable as in the outer block.
console.log(x); //=> 2
}
console.log(x); //=> 2
}
In the latest EcmaScript 6 (2015) standard, however, such blocks do have semantic value, as shown in the next example:
{
let x = 1;
{
let x = 2; // New variable, visible in this block only.
console.log(x); //=> 2
}
console.log(x); //=> 1
}
let and const are block-scoped variable declarations introduced by ES6.
The blocks are used just for statements like if(){}, function(){}, switch(){}, for(..){}, etc
.
In this example:
var number = 0;
if(true)
number = 1
else
number = 2
number = 3 //This line is evaluated because no longer is in the `else` condition
console.log(number); //3
Using blocks this will not happen:
var number = 0;
if(true)
{
number = 1
}
else
{
number = 2
number = 3
}
console.log(number); //1
Using blocks without using any statement are unnecessary, eg:
var foo = 2;
foo = 3;
console.log(foo) //3
It is the same as doing:
var foo = 2;
{
foo = 3;
}
console.log(foo) //3
Except if you are developing in an environment of ES6. Using let declarations in blocks are very important. And these will be evaluated only within the block.
let foo = 2;
{
let foo = 3;
}
console.log(foo) //2