Because let has block-level scope in if and for loops, es6 introduced let; var has no scope in if and for loops, and only the scope of function can be used to solve the reference scope. There is a problem with external variables, and let has a block-level scope. A "{}" is a scope.
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
Because var has no scope in if and for loops, only the scope of function can be used to solve the problem of referencing variables outside the scope; and let in If and for loops have block-level scope, which is a function that var does not have, so the let keyword is used instead of var in es6.
Because in previous JavaScript (before ES5), var did not have scope in if and for loops, and the problem of referencing variables outside the scope could only be solved by using the scope of function
Let was added to ES6, which has block-level scope in if and for. let has block-level scope. A {} is a scope, that is, let declares block-level variables, that is, local variables. .
const also has block-level scope. When our modified identifier does not want to be changed and assigned, use const
. It is recommended to use const first in ES6 development, only if you want to change one Let
The three major characteristics of let are only used when using identifiers:
The keyword used to declare variables must be declared first. Variables declared using
let have block-level scope
Temporary dead zone feature
Below I will analyze the children’s boots through the case:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>使用let关键字声明变量</title> </head> <body> <script> //let关键字用于声明变量的,使用let关键字声明的变量具有块级作用域 let num = 10; console.log(num); //错误使用let(let声明变量只在所处于的块级有效) if (true) { let nums = 100; } console.log(nums); //nums is not defined </script> </body> </html>
The browser controller runs as follows:
Note: var is used to declare global variables, not With block-level scope
// 在一个大括号中 // 使用let关键字声明的变量才具有块级作用域,var关键字是不具备这个特点的 if(true) { let a = 100;var b = 200; } console.log(a); consoLe.log(b);
The browser controller runs as follows:
[Related recommendations: javascript video tutorial, webfrontend】
The above is the detailed content of Why does es6 quote let?. For more information, please follow other related articles on the PHP Chinese website!