1 problem

Let’s start with the problems that can arise without block-level scope.

1.1 Inner variables overwrite outer variables

var temp=1;

function f(){
    console.log(temp);
    if(false){
        var temp='String variable';
    }
}
f()
Copy the code

Running results:

undefined

The variable temp in the body of the if statement overwrites the outer variable temp because the variable is promoted.

1.2 Count variables used for loops are actually global variables

var s = 'es6';
for (var i = 0; i < s.length; i++) {
    s[i];
}
console.log('i=' + i);
Copy the code

Running results:

i=3

Two block-level scopes

ES6 implements block-level scope through lets.

function f1() {
    let i = 1;

    if (true) {
        let i = 11;
    }
    console.log(i);
}

f1();
Copy the code

Running results:

1

The outer variable I is not affected by the inner variable I.

Use {… } structure, you can mark out a block-level scope. If a variable is not defined in the outer layer, a ReferenceError is raised: XXX is not defined. Look at the following example:

{{let str = 'hello'
    }
    console.log(str);
}
Copy the code

Running results:

console.log(str); ^ ReferenceError: str is not defined

The inner scope can define variables with the same name as the outer scope without affecting each other:

{
    let str='hello';
    {
        let str = 'How are you?';
        console.log('Inner:'+str);
    }
    console.log('Outer layer:'+str);
}
Copy the code

Running results:

Inner: How are you Outer: Hello

With block-level scope, we do not need IIFE (call function expressions immediately). IIFE is a JavaScript function that executes immediately when it is defined. Before there was no block-level scope, we used IIFE to simulate block-level scope.