How is this valid javascript, and what purpose does it serve?

后端 未结 2 508
盖世英雄少女心
盖世英雄少女心 2021-01-26 07:51

I was answering a question on quora and encountered something like following:

// if(true)
{
   var qq = 1;
}

Immediately I fired up chrome and

2条回答
  •  面向向阳花
    2021-01-26 08:31

    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
    

提交回复
热议问题