The variables declared by let and const are only valid within the code block.
{let a = 10;var b = 1;}a // ReferenceError: a is not defined.b // 1No variable promotion
Variables must be used after declaration, otherwise an error will be reported.
var tmp = 123;if (true) {tmp = 'abc'; // ReferenceErrorlet tmp;}Repeated statements are not allowed
// Error function () {let a = 10;var a = 1;}Block-level scope
function f() { console.log('I am outside!'); }(function () {if(false) {// Repeat the function function f() { console.log('I am inside!'); }}f();}());//I am inside! ES5 function promotion//I am outside! ES6 block-level scopeconst command
Declare a read-only constant. Once declared, the value of the constant cannot be changed.
Once a variable is declared, it must be initialized immediately and cannot be left to be assigned later.
Global variables declared by let command, const command, and class command, do not belong to the properties of the global object.
var a = 1;// If in Node's REPL environment, it can be written as global.a// or using a general method, it can be written as this.awindow.a // 1let b = 1;window.b // undefined
Next, I will introduce the const command of ES6 to you separately
JS, which has always been centered on ecma, has never had the concept of constants, and es6 has made up for this flaw;
const foo='foo';foo='bar';//TypeError: Assignment to constant variable.
The above example declares a constant of the basic type. If you try to modify the initial value, an error will be reported; if it is a value of the reference type, it also applies, but one thing needs to be paid attention to, give an example:
const foo=[]; foo=[1];//Assignment to constant variable.
A normal error, no problem, look again:
const foo=[1,2,3];foo[1]=4;console.log(foo)//[1, 4, 3]
Why is there no error in this? And can it be modified successfully? The difference between these two examples is that the former has changed the corresponding content of the pointer (need to be familiar with the js reference type) and the latter has not yet changed the pointing but the content of the pointing object has changed. For foo, I am just a pointer responsible for pointing to the corresponding object. As for the object content, I don’t care about my business, so I can modify it; if I don’t want the content to change, I can use another method;
const foo=Object.freeze([1,2,3]);foo[1]=4;console.log(foo)//[1, 2, 3]
This way you don't have to worry about being modified;