Skip to content Skip to sidebar Skip to footer

How Is This Valid Javascript, And What Purpose Does It Serve?

I was answering a question on quora and encountered something like following: // if(true) { var qq = 1; } Immediately I fired up chrome and tried the following { var qq = 1;

Solution 1:

The blocks are used just for statements like if(){}, function(){}, switch(){}, for(..){}, etc.

In this example:

varnumber = 0;
if(true)
    number = 1elsenumber = 2number = 3//This line is evaluated because no longer is in the `else` conditionconsole.log(number); //3

Using blocks this will not happen:

varnumber = 0;
if(true)
{
    number = 1
}
else
{
    number = 2number = 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

Solution 2:

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 :BlockStatementBlockStatement :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.

Post a Comment for "How Is This Valid Javascript, And What Purpose Does It Serve?"