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 // 1
There is no variable promotion
Variables must be declared after Use, otherwise an error will be reported
var tmp = 123; if (true) { tmp = 'abc'; // ReferenceError let tmp; }
Duplicate declaration is not allowed
// 报错 function () { let a = 10; var a = 1; }
Block-level scope
function f() { console.log('I am outside!'); } (function () { if(false) { // 重复声明一次函数f function f() { console.log('I am inside!'); } } f(); }()); //I am inside! ES5 函数提升 //I am outside! ES6 块级作用域
const 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 for later assignment
Global variables declared by the let command, const command, and class command are not attributes of the global object
var a = 1; // 如果在Node的REPL环境,可以写成global.a // 或者采用通用方法,写成this.a window.a // 1 let b = 1; window.b // undefined
Now I will introduce to you the const command of ES6 separately
JS with ecma as the core has always had no 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 basic type constant. If you try to modify the initial value, an error will be reported; if it is a reference type value, the same applies, but There is one thing to note. Here is an example:
const foo=[]; foo=[1];//Assignment to constant variable.
Normal error reporting, nothing wrong, look again:
const foo=[1,2,3]; foo[1]=4; console.log(foo)//[1, 4, 3]
How come there is no error? And can the modification be successful? The difference between these two examples is that the former has modified the pointer (you need to be familiar with js reference types) and the corresponding content has changed, while the latter does not point to the same but the content of the object has changed. For foo, I just A pointer is responsible for pointing to the corresponding object. As for the content of the object, it doesn’t matter to me, so it can be modified; if you don’t want the content to change, you can use another method;
const foo=Object.freeze([1,2,3]); foo[1]=4; console.log(foo)//[1, 2, 3]
So you don’t have to worry about being modified;
For more in-depth articles on let and const commands in ES6, please pay attention to the PHP Chinese website!