ES5 only has global scope and function scope, and no block-level scope, which makes many scenarios unreasonable.
The first scenario: inner variables may override outer variables.
var tmp = new Date(); function f(){ console.log(tmp); if (false) { var tmp = 'hello world'; } } f(); //undefined
The second scenario: the loop variable used for counting is leaked as a global variable.
var s = 'hello'; for (var i = 0; i < s.length; i++) { console.log(s[i]); } console.log(i); // 5 The variable i is only used to control the loop, but when the loop ends, it does not disappear, but the global variable is leaked.
ES6 block scope
let actually adds block-level scoping to JavaScript.
function f1(){ let n =5; if (true) { let n = 10; } console.log(n); //5 }
ES6 allows arbitrary nesting of block scopes.
{{{let in = 'hello'}}};
Inner scopes can define variables of the same name in outer scopes.
{{ let in = 'hello'; {let in = 'hello'} }};Block scope and function declarations
ES5 stipulates that functions can only be declared in top-level scope and function-scoped value, not in block-level scope.
ES6 introduces block scope, which explicitly allows functions to be declared inside block scope. ES6 stipulates that in block-level scope, function declaration statements behave like let and cannot be referenced outside of block-level scope.
Note: ES6's block-level scope allows functions to be declared only when curly braces are used. If curly braces are not used, an error will be reported.
do expression
A block scope is a statement that encapsulates multiple operations with no return value.
Using block-level scope can become an expression, that is, you can return a value, by adding do before the block-level scope, it becomes a do expression.
let x = do{ let t =f(); t * t + 1; } //The variable x will get the return value of the entire block-level action.