Try to share something when I get something to share

ES6 bring in a new scope based on block, before that we only have global and local scope.

The blocked scope declares by let, and below are the goodies:

1.

function hi(){
    let hi = 10;
    let hi = 20; // error out : let cannot be re-declare, var can
    }

2-1.

function hi(){
    let hi = 10;
    if(true){
        let hi = 20;
    }
    console.log(hi);  // log 10;
}

2-2.

function hi(){
    let hi = 10;
    if(true){
        hi = 20;
    }
    console.log(hi); // log 20;
}

3-1.

for(let i = 0; i< 10; i++){
    setTimeout(
    function a() {
        console.log(i); //print 0 to 9
    }, 100 * i);
}

3-2.

for(var i = 0; i< 10; i++){
    setTimeout(
    function a() {
        console.log(i); //print 10 by 10 times
    }, 100 * i);
}

Generally, var is less recommended:

        if( can use const) use const
        else if( can use let) use let
        else use var 

So far, very rare case this could happen, I have to learn more stuff to tell in which specific case, this happens.

Nothing new, just a summary of what I think of all the daily readings.
All above is just for beginners like me. Any meaningful comments are much welcomed and appreciated.

Thanks,


liudaxingtx
45 声望1 粉丝

新菜