Home  >  Article  >  Web Front-end  >  What is the difference between let and var in es6

What is the difference between let and var in es6

青灯夜游
青灯夜游Original
2022-04-15 19:42:262178browse

Difference: 1. let variables have block-level scope, while var variables do not have block-level scope; 2. var variables have variable promotion (no temporary dead zone constraints) and can be used first and then declared, while Let variables do not have variable promotion (there are temporary dead zone constraints) and must be declared before use; 3. Let variables cannot be declared repeatedly, but var variables can.

What is the difference between let and var in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

ES6 adds the let command to declare local variables. Its usage is similar to var, but the declared variable is only valid within the code block where the let command is located (block-level scope), and has temporary dead zone constraints .

Let’s take a look at var’s common variable improvement interview questions:

题目1:
var a = 99;            // 全局变量a
f();                   // f是函数,虽然定义在调用的后面,但是函数声明会提升到作用域的顶部。 
console.log(a);        // a=>99,  此时是全局变量的a
function f() {
  console.log(a);      // 当前的a变量是下面变量a声明提升后,默认值undefined
  var a = 10;
  console.log(a);      // a => 10
}

// 输出结果:
undefined
10
99

If you have difficulty understanding the above questions, please take a systematic look at Lao Ma’s free JS Advanced video tutorials.

ES6 can use let to define block-level scope variables

Before ES6, we used var to declare variables, and JS only Function scope and global scope do not have block-level scope, so {} cannot limit the access scope of variables declared by var.
For example:

{ 
  var i = 9;
} 
console.log(i);  // 9

ES6’s new let can declare block-level variables.

{ 
  let i = 9;     // i变量只在 花括号内有效!!!
} 
console.log(i);  // Uncaught ReferenceError: i is not defined

let Unique application with for loop

letIt is very suitable for block-level functions inside the for loop area. The for loop body in JS is special. Each execution is a new independent block scope. After the variables declared with let are passed into the scope of the for loop body, they will not change and will not be affected by the outside world. Look at a common interview question:

for (var i = 0; i <10; i++) {  
  setTimeout(function() {  // 同步注册回调函数到 异步的 宏任务队列。
    console.log(i);        // 执行此代码时,同步代码for循环已经执行完成
  }, 0);
}
// 输出结果
10   共10个
// 这里面的知识点: JS的事件循环机制,setTimeout的机制等

If var is changed to letStatement:

// i虽然在全局作用域声明,但是在for循环体局部作用域中使用的时候,变量会被固定,不受外界干扰。
for (let i = 0; i < 10; i++) { 
  setTimeout(function() {
    console.log(i);    //  i 是循环体内局部作用域,不受外界影响。
  }, 0);
}
// 输出结果:
0  1  2  3  4  5  6  7  8 9

let has no variables Promotion and temporary dead zone

There is no variable promotion for variables declared with let. And it is required that the variable cannot be used until the let declaration statement is executed, otherwise an Uncaught ReferenceError error will be reported.

For example:

console.log(aicoder);    // 错误:Uncaught ReferenceError ...
let aicoder = &#39;aicoder.com&#39;;
// 这里就可以安全使用aicoder

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 the "temporary dead zone" (TDZ).

let variables cannot be declared repeatedly

let does not allow repeated declaration of the same variable in the same scope. Otherwise, an error is reported: Uncaught SyntaxError: Identifier 'XXX' has already been declared

For example:

let a = 0;
let a = &#39;sss&#39;;
// Uncaught SyntaxError: Identifier &#39;a&#39; has already been declared

Summary

ES6's let allows js to truly have a block-level scope, which is also a safer and more standardized path. Although many constraints are added, they are all designed to allow us to use and write code more safely.

【Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of What is the difference between let and var 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