I was answering a question on quora and encountered something like following:
// if(true)
{
var qq = 1;
}
Immediately I fired up chrome and
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