grammar
let variable1 = value1
parameter
variable1
The name of the variable to declare.
value1
The initial value assigned to the variable.
Remark
Use a let statement to declare a variable whose scope is limited to the block that declares it. You can assign values to variables when declaring variables, or you can assign values to variables later in the script.
Variables declared using let cannot be used before declaration, otherwise an error will be caused.
If your variable is not initialized in the let statement, it will be automatically assigned a JavaScript value undefined.
Example:
var l = 10;{ let l = 2; // At this point, l = 2.}// At this point, l = 10.// Additional ways to declare a variable using let.let index;let name = "Thomas Jefferson";let answer = 42, counter, numpages = 10;let myarray = new Array();Block-level scope
for(var i = 0; i < 10; i++){}console.log(i); //10for(let j = 0; j < 10; j++){}console.log(j); //"ReferenceError: j is not definedNo variable promotion
console.log(a); // Output undefinedconsole.log(b); // Error ReferenceErrorconsole.log(c); // Error ReferenceErrorvar a = 2;let b = 2;
Pay attention to the difference between undefined and ReferenceError
Temporary dead zone (TDZ)
As long as you enter the current block-level scope, the variables used already exist, but they are dead zones before declaration and cannot be operated.
Note: typeof is no longer a 100% safe operation
typeof x; // ReferenceErrortypeof y // undefinedlet x;
Repeated statements are not allowed
let x = 1;let x; // "SyntaxError: Identifier 'x' has already been declaredvar y = 2;var y = 3; // y = 3
Block-level scope
// Anonymous function writing (function () { var tmp = ...; ...}());// Block-level scope writing { let tmp = ...; ...}ES5's strict mode stipulates that functions can only be declared within the top-level scope and function, and declarations in other situations (such as if code blocks, loop code blocks) will report errors.
// ES5'use strict';if (true) { function f() {} // Report an error}Since ES6 introduces a block-level scope, this situation can be understood as a function declared within a block-level scope, so no error is reported, but the braces that make up the block cannot be missing.
// Report an error 'use strict';if (true) function f() {}The declared global variable is no longer a property of window
"use strict";var a = 1;console.log(window.a) // 1let b = 1;console.log(window.b) // undefined