Many languages have block-level scopes, but JS does not, it uses VAR to declare variables, the function to divide the scope, curly braces "{}" does not limit the scope of var. Variables declared with VAR have the effect of variable promotion (declaration hoisting).
A let is added to the ES6, which can be declared in {}, if, for. The usage is the same as Var, but scoped at the block level, the let declared variable does not have a variable promotion.
Example 1: block-level scope if
function Getval (boo) {if (boo) {var val = ' red '//... return val} else {//Here you can access Valreturn null}//here can also access Val}
The variable Val is declared in the If block, but can be accessed to Val outside of the else block and if.
Change Var to let, that's it.
function Getval (boo) {if (boo) {Let val = ' red '//... return val} else {//here access not to Valreturn null}//here also cannot access Val}
Example 2: block-level scope for
function func (arr) {for (var i = 0; i < arr.length; i++) {//I ...} This can also be accessed to i}
The variable i is declared in the for block, but can also be accessed for outside.
I cannot be accessed by replacing VAR with let,for.
function func (arr) {for (Let i = 0; i < arr.length; i++) {//I ...} No access to i} here
Example 3: Variable promotion (declared after use)
function func () {//Val first declared after use, no Error alert (val)//Undefinedvar Val;}
The variable Val is declared after the first use, output undefined, and no error.
Change Var to let, it's an error.
The function func () {//Val is declared after the first use, reporting syntax error alert (val) let Val;}
Example 4: variable Promotion (first judgment and later declaration)
function func () {if (typeof val = = ' undefined ') {//...} var val = '}
You can also use TypeOf to determine the front of the Var statement
But change the Var to let,if and report grammatical errors.
function func () {if (typeof val = = ' undefined ') {//...} Let val = ';}
ES6 rules that if let is present in a code block, the chunk forms a closed scope from the beginning. Any use before the declaration, will be an error. That is, within a code block, using a variable before a let declaration is not available. There is a grammatical term called "temporary Dead Zone" (temporal dead Zone), referred to as TDZ. Of course Tdz does not appear in the ES specification, it is only used to describe the image.
Let's considerations
1. Cannot repeat the declaration
var and let duplicate declaration var name = ' Jack '; let name = ' John ';//two let repeat declaration let-age = 24;let age = 30;
Execution times syntax error
2. With let, the anonymous function can be removed from execution.
anonymous function notation (function () { var jQuery = function () {}; // ... window.$ = jquery});//block-scoped notation {let jQuery = function () {}; // ... window.$ = JQuery;}
Related:
6 Properties of a variable
ES6 block-level scope and new variable declaration (let)