ES6 let, const declare a variable;
Let and const variable declarations
Let variable declaration
- Let declares block-level scoped variables, with braces as blocks
{// block level scope let x = 10; let y = 20; }Copy the code
- Variables declared by let cannot be used in advance to be more rigorous
console.log(x); var x = 10; console.log(y); Y is not defined let y = 20Copy the code
- Using let to declare the same variable in the same scope results in an error.
function foo(){ let x = 10; let x = 20; } foo(); // Identifier 'x' has already been declaredCopy the code
- Var variable declarations are executed ahead of time, but let is not
let x = 10; console.log(y); // The Identifier 'x' has already been declared console.log(z); // undefined if(false){ let y = 20; var z = 30 }Copy the code
Const variable declaration
- Const is used to declare constants.
- A const declaration variable must be initialized immediately and its value cannot be changed.
Const PI = 3.14Copy the code
Global object properties
- Global variables declared by the var and function commands are still properties of global objects.
- Global variables declared by let, const, and class commands are not properties of global objects.
var x = 10; let y = 20; console.log(window.x); // 10 console.log(window.y); // undefinedCopy the code