Home  >  Article  >  Web Front-end  >  How to use let in es6

How to use let in es6

青灯夜游
青灯夜游Original
2023-01-12 19:10:301549browse

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.

How to use let in es6

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.

forThe 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

letThere 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 = &#39;abc&#39;; // 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 = &#39;abc&#39;; // 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规定暂时性死区和letconst语句不出现变量提升,主要是为了减少运行时错误,防止在变量声明前就使用这个变量,从而导致意料之外的行为。这样的错误在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 = &#39;hello&#39;;

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 = &#39;Hello World&#39;}}}}};

上面代码使用了一个五层的块级作用域。外层作用域无法读取内层作用域的变量。

{{{{
  {let insane = &#39;Hello World&#39;}
  console.log(insane); // 报错
}}}};

内层作用域可以定义外层作用域的同名变量。

{{{{
  let insane = &#39;Hello World&#39;;
  {let insane = &#39;Hello World&#39;}
}}}};

块级作用域的出现,实际上使得获得广泛应用的立即执行函数表达式(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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn