How to use let in es6
In es6, the let keyword is used to declare variables; however, the declared variables are only valid within the code block where the let command is located. Let does not cause "variable promotion", so variables must be used after they are declared, otherwise an error will be reported. As long as the let command exists in the block-level scope, the variables declared by it are "binding" to this area and are no longer affected by external influences.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 let keyword
ES6 adds a new let
command to declare variables. Its usage is similar to var
, but the declared variable is only valid within the code block where the let
command is located.
{ let a = 10; var b = 1; } a // ReferenceError: a is not defined. b // 1
The above code is in the code block and declares two variables with let
and var
respectively. Then these two variables are called outside the code block. As a result, the variable declared by let
reports an error, and the variable declared by var
returns the correct value. This shows that the variable declared by let
is only valid in the code block in which it is located.
for
The counter of the loop is very suitable to use the let
command.
for (let i = 0; i < 10; i++) {} console.log(i); //ReferenceError: i is not defined
In the above code, the counter i
is only valid within the body of the for
loop, and an error will be reported when referenced outside the loop.
If the following code uses var
, the final output is 10.
var a = []; for (var i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 10
In the above code, the variable i
is declared by var
and is valid in the global scope. So every time it loops, the new i
value will overwrite the old value, causing the final output to be the value of the last round of i
.
If let
is used, the declared variable is only valid within the block-level scope, and the final output is 6.
var a = []; for (let i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 6
In the above code, the variable i
is declared by let
. The current i
is only valid in this cycle, so every cycle The i
is actually a new variable, so the final output is 6.
No variable promotion
let
There is no "variable promotion" phenomenon like var
. Therefore, variables must be used after they are declared, otherwise an error will be reported.
console.log(foo); // 输出undefined console.log(bar); // 报错ReferenceError var foo = 2; let bar = 2;
In the above code, the variable foo
is declared with the var
command, and variable promotion will occur. That is, when the script starts running, the variable foo
has been It exists, but has no value, so undefined
will be output. The variable bar
is declared with the let
command, and no variable promotion will occur. This means that the variable bar
does not exist before declaring it, and if it is used, an error will be thrown.
Temporary dead zone
As long as the let
command exists in the block-level scope, the variables declared by it are "binding" This area is no longer affected by external influences.
var tmp = 123; if (true) { tmp = 'abc'; // ReferenceError let tmp; }
In the above code, there is a global variable tmp
, but let
declares a local variable tmp
in the block-level scope, resulting in the following Or bind this block-level scope, so before let
declares the variable, assigning a value to tmp
will report an error.
ES6 clearly stipulates that if there are let
and const
commands in a block, this block will have a closed effect on the variables declared by these commands from the beginning. area. Any use of these variables before declaration will result in an error.
In short, within the code block, the variable is not available until it is declared using the let command. Grammatically, this is called a "temporary dead zone" (TDZ).
if (true) { // TDZ开始 tmp = 'abc'; // ReferenceError console.log(tmp); // ReferenceError let tmp; // TDZ结束 console.log(tmp); // undefined tmp = 123; console.log(tmp); // 123 }
In the above code, before the let
command declares the variable tmp
, it belongs to the "dead zone" of the variable tmp
.
"Temporary dead zone" also means that typeof
is no longer a 100% safe operation.
typeof x; // ReferenceError let x;
In the above code, the variable x
is declared using the let
command, so before it is declared, it belongs to the "dead zone" of x
. As long as you use An error will be reported when reaching this variable. Therefore, typeof
will throw a ReferenceError
when run.
For comparison, if a variable is not declared at all, using typeof
will not report an error.
typeof undeclared_variable // "undefined"
In the above code, undeclared_variable
is a variable name that does not exist, and the result is "undefined". Therefore, before let
, the typeof
operator was 100% safe and would never report an error. This is no longer true. This design is to help everyone develop good programming habits. Variables must be used after they are declared, otherwise an error will be reported.
Some "dead zones" are hidden and not easy to find.
function bar(x = y, y = 2) { return [x, y]; } bar(); // 报错
上面代码中,调用bar
函数之所以报错(某些实现可能不报错),是因为参数x
默认值等于另一个参数y
,而此时y
还没有声明,属于”死区“。如果y
的默认值是x
,就不会报错,因为此时x
已经声明了。
function bar(x = 2, y = x) { return [x, y]; } bar(); // [2, 2]
ES6规定暂时性死区和let
、const
语句不出现变量提升,主要是为了减少运行时错误,防止在变量声明前就使用这个变量,从而导致意料之外的行为。这样的错误在ES5是很常见的,现在有了这种规定,避免此类错误就很容易了。
总之,暂时性死区的本质就是,只要一进入当前作用域,所要使用的变量就已经存在了,但是不可获取,只有等到声明变量的那一行代码出现,才可以获取和使用该变量。
不允许重复声明
let不允许在相同作用域内,重复声明同一个变量。
// 报错 function () { let a = 10; var a = 1; } // 报错 function () { let a = 10; let a = 1; }
因此,不能在函数内部重新声明参数。
function func(arg) { let arg; // 报错 } function func(arg) { { let arg; // 不报错 } }
块级作用域
为什么需要块级作用域?
ES5只有全局作用域和函数作用域,没有块级作用域,这带来很多不合理的场景。
第一种场景,内层变量可能会覆盖外层变量。
var tmp = new Date(); function f() { console.log(tmp); if (false) { var tmp = "hello world"; } } f(); // undefined
上面代码中,函数f执行后,输出结果为undefined
,原因在于变量提升,导致内层的tmp变量覆盖了外层的tmp变量。
第二种场景,用来计数的循环变量泄露为全局变量。
var s = 'hello'; for (var i = 0; i < s.length; i++) { console.log(s[i]); } console.log(i); // 5
上面代码中,变量i只用来控制循环,但是循环结束后,它并没有消失,泄露成了全局变量。
ES6的块级作用域
let
实际上为JavaScript新增了块级作用域。
function f1() { let n = 5; if (true) { let n = 10; } console.log(n); // 5 }
上面的函数有两个代码块,都声明了变量n
,运行后输出5。这表示外层代码块不受内层代码块的影响。如果使用var
定义变量n
,最后输出的值就是10。
ES6允许块级作用域的任意嵌套。
{{{{{let insane = 'Hello World'}}}}};
上面代码使用了一个五层的块级作用域。外层作用域无法读取内层作用域的变量。
{{{{ {let insane = 'Hello World'} console.log(insane); // 报错 }}}};
内层作用域可以定义外层作用域的同名变量。
{{{{ let insane = 'Hello World'; {let insane = 'Hello World'} }}}};
块级作用域的出现,实际上使得获得广泛应用的立即执行函数表达式(IIFE)不再必要了。
// IIFE 写法 (function () { var tmp = ...; ... }()); // 块级作用域写法 { let tmp = ...; ... }
【相关推荐:javascript视频教程、编程视频】
The above is the detailed content of How to use let in es6. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

No, require is the modular syntax of the CommonJS specification; and the modular syntax of the es6 specification is import. require is loaded at runtime, and import is loaded at compile time; require can be written anywhere in the code, import can only be written at the top of the file and cannot be used in conditional statements or function scopes; module attributes are introduced only when require is run. Therefore, the performance is relatively low. The properties of the module introduced during import compilation have slightly higher performance.

The map is ordered. The map type in ES6 is an ordered list that stores many key-value pairs. The key names and corresponding values support all data types; the equivalence of key names is determined by calling the "Objext.is()" method. Implemented, so the number 5 and the string "5" will be judged as two types, and can appear in the program as two independent keys.
