preface
I am a PHP programmer, recently in the study of front-end knowledge, so tao this ruan yifeng teacher wrote “ES6 standard entry”, the book is particularly good, in this record some get knowledge points, I hope to be helpful to everyone. Let and const are new commands that have been added to ES6. You may have been familiar with them before, but this article will make you understand them better.
1. Let the order
1.1 Basic Usage
ES6 added the let command, which is similar to var for declaring variables, but unlike var, the declared variables are only valid within the code block where the let is.
{
let a = 1;
var b = 2;
// Code block internal call
console.log(a); / / 1
console.log(b); / / 2
}
// Code block external call
console.log(a); //ReferenceError: a is not defined
console.log(b); / / 2
Copy the code
The above code declares two variables in the code block using let and var, and then calls both variables inside and outside the code block. Internally it can be called correctly; Externally, however, variables declared using let report errors and var prints correctly. Note The variables declared by the LET are valid only within the block.
1.2 There is no variable promotion
The var command can be “promoted” (undefined) before the variable is declared. It is not logical to call a variable without declaring it. To correct this, let changes the syntax behavior so that variables it declares can only be used after they have been declared, otherwise an error will be reported.
/ / var
console.log(foo); //undefined
var foo = 2;
/ / let's situation
console.log(foo2); //ReferenceError: Cannot access 'foo2' before initialization
let foo2 = 10;
Copy the code
Foo uses var to declare variable promotion, so it prints undefined; However, when foo2 is declared with let, there is no variable promotion. This means that the variable foo2 does not exist before it is declared, and an error will be thrown if it is used.
1.3 Temporary dead zone
As long as a let command exists in a block-level scope, the variables it declares are bound to the scope, free from external influence.
// Temporary dead zone
var tmp = 123;
if (true) {
tmp = 'abc'; //ReferenceError: Cannot access 'tmp' before initialization
let tmp;//
}
Copy the code
In the above code, the global variable TMP exists, but in the block-level scope, let declared a local variable TMP, causing the latter to bind to the block-level scope, so the assignment of TMP before let declared the variable will report an error. ES6 explicitly states that if there are let and const commands in a block, the variables declared by those commands are closed from the start, and an error will be reported whenever they are used before the declaration.
1.4 Duplicate declarations are not allowed
Let does not allow the same variable to be declared twice in the same scope.
/ / an error
{
let a = 10;
var a = 20; //SyntaxError: Identifier 'a' has already been declared
}
/ / an error() = > {let a = 10;
let a = 1; //SyntaxError: Identifier 'a' has already been declared
}
Copy the code
Therefore, arguments cannot be redeclared inside functions.
/ / an error
(a) => {
let a = 10; //SyntaxError: Identifier 'a' has already been declared
}
/ / is not an error
(a) => {const PI = 3.1415;
PI = 3; //TypeError: Assignment to constant variable.
{
let a = 10; }}Copy the code
2. The const command
2.1 Basic Usage
Const declares a read-only constant. Once declared, the value of the constant cannot be modified.
const PI = 3.1415;
PI = 3; //TypeError: Assignment to constant variable.
Copy the code
As you can see from the above code, changing the value of a constant causes an error.
const FOO; //SyntaxError: Missing initializer in const declaration
Copy the code
Const declaring a constant without assigning also raises an error.
2.2 nature
Const does not inherently guarantee that the value of a variable cannot be changed, but that the memory address to which the variable points cannot be changed. For simple data types (values, strings, booleans), values are stored in the memory address that the variable points to, and are therefore equivalent to constants. But in the case of composite types (objects and arrays), the memory address a variable points to is just a pointer. Const guarantees that the pointer is fixed, and does not control whether the data structure it points to is mutable.
const FOO = {};
// Add a name attribute to FOO
FOO.name = 'neo';
console.log(FOO.name); //neo
// Set FOO to another object
FOO = {}; //TypeError: Assignment to constant variable.
Copy the code
In the code above, the constant FOO stores an address that points to an object. The address is immutable, but the object itself is mutable and can still be assigned attributes. Let’s look at an array example
const A = [];
A.push('neo'); / / the executable
A.length = 0; / / the executable
A = ['aliy']; //TypeError: Assignment to constant variable.
Copy the code
In the above code, A is an array, and the array itself is writable. Assigning another array to A will result in an error.
PS: How do you freeze an object so it can’t be modified? Use the object.freeze method.
const FOO = Object.freeze({});
// In normal mode, the following line of code does not take effect
In strict mode, the following line of code will report an error
FOO.name = 'neo';
console.log(FOO) // Output is {}
Copy the code
In the code above, the constant FOO refers to a frozen object, so adding new attributes does not work and will cause an error in strict mode. In addition to freezing the object itself, properties of the object should also be frozen. Here is a function that freezes the object completely.
var constantize = (obj) = > {
Object.freeze(obj);
Object.keys(obj).forEach( (key, i) = > {
if( typeof obj[key] === 'object') { constantize(obj[key]); }}); }const neo = {name:"neo".test: {}}; constantize(neo) neo.test.age=23;
console.log(neo)
23. If we want to use the function constantize, the output is {name: 'neo', test: {}}
// otherwise {name: 'neo', test: {age: 23}}
Copy the code
Personal summary
- It is better to use let and const to define variables and constants in if and for loops and inside functions to prevent memory leakage (for example, var is used to declare variables in the for loop, which is a global variable and always exists in memory after the loop ends) and variable promotion.
- When defining an object or array using const, pay attention to the corresponding property changes.