Summary of common ES6 features

I. ES6 Basic Understanding

1. What is ES6?

ES6 refers to ECMAScript 6.0 and is a standard for the JavaScript language.The goal is to make JavaScript a language for enterprise development by allowing you to write complex, large applications.

2. What is the difference between ES6 and JavaScript?

ES6 is a standard for JavaScript, and JavaScript is a concrete implementation of ES6.

3. Babel Transcoder?

Babel is a widely used ES6 transcoder that converts ES6 code to ES5 code to execute in an existing environment, even if you write code in ES6 without worrying about not running.
Simply put, some browsers do not support ES6 grammar, so they can use Babel Transcoder to convert ES6 grammar to ES5 grammar, which is recognized by the browser.
For example:

ES6 can use the arrow function instead of the normal function, which can be converted to the normal function through the Babel Transcoder.This way, you don't have to worry about whether your browser supports this syntax.

[ES6]
    input.map(item => item + 1);

[ES5]
    input.map(function (item) {
        return item + 1;
    });

 

2. Common characteristics

1. let command

(1) Basic Contents
The let command is usually used to declare local variables.
Features: Locally valid, no variable promotion, temporary dead zone, no duplicate declaration allowed.

(2) Feature 1: Locally effective.
The let command is similar to var in that it declares variables, but var is globally valid and lets only work within the block of code in which they are located and cannot get the value.

Here's an example: (Look around a little, look twice more)
var defines a global variable, and for a for loop, the entire loop operates on only one variable.Look at the first cycle in the example below. Operating i inside a cycle affects the circulation.Because i++ was done twice, some values of the array were empty and only a partial loop was made.

Lets define local variables. For a for loop, each loop is a different scope, and lets are valid only for the current scope.More interestingly, inside a loop statement is a sub-scope (that is, a let variable with the same name is defined internally, without affecting the external let variable).Look at the second loop in the example below. j is a different value for each loop operation, and the let variable j with the same name is defined inside the loop. Due to scope issues, it does not affect j in the loop statement, so all loops are executed.

[Examples:

var a = [];             // Used to record the initial value to be printed for each loop
var b = [];             // Used to record the initial value of each loop
var count = 0;          // Number of loops to record

for(var i = 0; i < 10; i++, count++) {
    a[i] = function() {
        console.log("Value of current loop i For:  " + i);
    };
    b[i] = i++; 
}
console.log("The current number of loops executed is:  " + count);           // Because i For global variables, each loop occurs twice i++,So the actual number of loops is less than 10, so the output is 5
a[6]();                                                // Since all operations are the same variable, the function call was last modified i Value, so the output is 10
console.log("Initial value for each loop i For:  " + b);            // Used for partial loops where some of the arrays are not assigned, i.e. null.So the output is zero,,2,,4,,6,,8
console.log("After loop execution i Value:  " + i);                // i = 10 Exit the loop at i Is a global variable, so the output is 10


var c = [];            // Used to record the initial value to be printed for each loop
var d = [];            // Used to record the initial value of each loop
var count = 0;         // Number of loops to record
for(let j = 0; j < 10; j++, count++) {
    let j = 5;
    c[j] = function() {
        console.log("Value of current loop j For:  " + j);
    };
    d[j] = j++; 
}
console.log("The current number of loops executed is:  " + count);           // Because j For local variables, defined within a loop let Variable with the same name j (Subscope) does not affect the loop statement's j,The real loop executes 10 times, so the output is 10 
c[5]();                                                // Each operation is a different variable and executed j++ Operation, so the output is 6
console.log("Initial value for each loop j For:  " + d);            // Because inside gives d[5] Assignment, the rest of the elements are null, so the output is  ,,,,,5
console.log("After loop execution j value:  " + j);                // Because j Is a local variable and can only exist in for Loop code block, so error here, output ReferenceError: j is not defined

 

 

 

(3) Feature 2: There is no variable promotion
Variable promotion means that a variable can be used before it is declared.
There is no variable promotion for let, that is, variable can be used only after it is declared, not before it is declared, otherwise an error will occur.

[Examples:

console.log(a);     // No error, output undefined
console.log(b);     // Error, Output ReferenceError: b is not defined
var a = 10;
let b = 20;

 

 

 

(4) Feature 3: Transient Dead Zone
Transient Dead Zone refers to a variable that already exists when it first enters the current scope but cannot be obtained until it is declared.

[Example:]

var tmp = 123;
console.log(tmp); //no error, output 123
if (true) {
    console.log(tmp); //Error, ReferenceError: Cannot access'tmp'before initialization
    let tmp;
}

The first time tmp is defined as var type, so it can output 123 normally.
After entering the if statement, because there is a tmp defined by let, the system determines that tmp is a local variable rather than a global variable.
Causes TMP in console.log(tmp) to appear before a variable declaration (variable promotion fails), causing an error, which is a temporary dead zone.

 

 

 

(5) Feature 4: No duplicate declaration
In the same block let scope, if a variable is declared with a let, the same variable cannot be declared repeatedly.

[Examples:
// Report errors, Identifier 'a' has already been declared
{
    let a = 1;
    var a = 2;
}

// No error, undefined
{
    var a = 1;
    var a = 2;
}

// Report errors, Identifier 'a' has already been declared
{
    let a = 1;
    let a = 2;
}

 

2. const command

(1) Basic Contents
const is usually used to declare a read-only constant. Once declared, the value of the constant cannot be modified and must be initialized when declared.
Similar to let, locally valid, no variable promotion, no duplicate declaration.

[Examples: (Constant values cannot be modified)

const PI = 3.1415926
console.log(PI);   // Output 3.1415926
PI = 3.14          // Error, Output Assignment to constant variable.

[Example: (Initialization required for constant declaration)

const a           // Error, Output Missing initializer in const declaration

[Example: Locally effective)
{
    const PI = 3.1415926;
}
console.log(PI);   // Error, Output PI is not defined

[Example: No Variable Promotion)
{
    console.log(PI);    // Error, Output Cannot access 'PI' before initialization
    const PI = 3.1415926;
}

[Example: no duplicate declaration)
{
    var PI = 3.14
    const PI = 3.1415926;  // Error, Output SyntaxError: Identifier 'PI' has already been declared
}

  

(2) If const declares an object, then it does not change the address pointing to the object, and the value of the object can still change.Objects can be frozen (that is, they cannot be modified) through the object.freeze() method.

[Give an example:var,Objects can be modified)
{
    var f = {name : 'tom', age : '12'};
    console.log(f.name + ", " + f.age);   // tom, 12
    f.name = 'jarry';
    f.age = 44;
    console.log(f.name + ", " + f.age);  // jarry, 44
    f = {name : 'rick', age : '22'};
    console.log(f.name + ", " + f.age);  // rick, 22
}

[Give an example: const,Object contents can be modified, but objects cannot be modified)
{
    const f = {name : 'tom', age : '12'};
    console.log(f.name + ", " + f.age);   // tom, 12
    f.name = 'jarry';
    f.age = 44;
    console.log(f.name + ", " + f.age);  // jarry, 44
    f = {name : 'rick', age : '22'};  // TypeError: Assignment to constant variable.
}

[Give an example: freeze,Object cannot be modified,Object content cannot be modified)
{
    const f = Object.freeze({name : 'tom', age : '12'});
    console.log(f.name + ", " + f.age);  // tom, 12
    f.name = 'jarry';
    f.age = 44;
    console.log(f.name + ", " + f.age);  // tom, 12
    f = {name : 'rick', age : '22'};  // TypeError: Assignment to constant variable.
}

 

 

 

3. Deconstruction Expression

(1) What is deconstruction?
Deconstruction refers to ES6's support for extracting values from arrays or objects according to a pattern and assigning the extracted values to variables.

(2) Deconstruction assignment of arrays
In general, as long as the = left and right modes are the same, the variable on the left will assign the corresponding value on the upper and right.

[Assignment not using a deconstruction expression:]
let a = 10;
let b = 20;
let c = 30;
console.log(a, b, c);

[Assignment using a deconstruction expression:]
let [a, b, c] = [100, 200, 300];
console.log(a, b, c);

 

 

 

When the deconstruction is unsuccessful, the corresponding data is undefined.
Allows deconstruction assignments to specify default values, which can be a function (lazy, called only when used).

[Nested Array Assignment:]

let [a, [b, [c, d]]] =  [1, [2, [3, 4]]];
console.log(a, b, c, d);         // Output 1 2 3 4

let [head, ...tail] = [1, 2, 3, 4];
console.log(head);    // Output 1
console.log(tail);    // output (3) [2, 3, 4]

let [x, y, ...z] = [1];
console.log(x);        // Output 1
console.log(y);        // output undefined
console.log(z);        // output []

[Partial deconstruction:(Assigning values to variables on a match)]

let [x, y, z] = [1, 2];
console.log(x);       // Output 1
console.log(y);       // Output 2
console.log(z);       // output undefined

let [a, [b], c] = [1, [2, 3], 4];
console.log(a);       // Output 1
console.log(b);       // Output 2
console.log(c);       // Output 4

[Default values are used for deconstruction: (i.e. default values can be used if assignment fails)

function hello() {
    return "hello";
}

let [x=hello(), y=hello(), z=100] = [1, 2, 3];
console.log(x);               // Output 1
console.log(y);               // Output 2
console.log(z);               // Output 3

let [x2=hello(), y2=hello(), z2=100] = [, 2, ];
console.log(x2);              // output hello
console.log(y2);              // Output 2
console.log(z2);              // Output 100

 

(3) Deconstruction assignment of objects
Objects can also be deconstructed.Unlike array deconstruction, objects are deconstructed by matching attribute names without attention to order.
The value is undefined when the attribute name does not match.
You can customize the attribute name by using: to specify.
As an example:
let {name, age} is equivalent to let {name: name, age: age}

[Match by attribute name:]

let {name, age} = {name: "tom", age: 22};
console.log(name);               // output tom
console.log(age);                // Output 22

[Property name matching unsuccessful, return undefined: ]
let {name2, age2} = {name: "tom", age: 22};
console.log(name2);               // output undefined
console.log(age2);                // output undefined

[Custom attribute name matching:]
let {name: name3, age: age3} = {name: "tom", age: 22};
console.log(name3);               // output tom
console.log(age3);                // Output 22

 

 

 

4. String Expansion

String processing is enhanced.
(1) unicode representation of characters
JavaScript allows a character to be represented as \uxxxx, where xxxx represents the unicode value.However, this writing only supports \u0000 ~\uffff, beyond which double bytes are required.
For example:

_1F680 resolves to_1F68 and 0.For normal display, use double-byte \uD83D\uDE80.

[Examples:

console.log("\u0061");       // output a
console.log("\u00614");      // output a4

 

 

 

ES6 can be correctly interpreted by enclosing XXXX in curly braces.

[Examples:

console.log("\u{0061}");
console.log("\u{1F680}");
console.log("\uD83D\uDE80");

 

 

 

(2) New methods include(), startsWith(), endsWith()
indexOf() is used in JavaScript to determine if a string contains another string.
ES6 adds three new methods to determine if a string contains another string.
includes() returns a Boolean value, true indicates that another string exists in the current string, and false indicates that it does not exist.
startsWith() returns a Boolean value, true indicates that another string exists at the head of the current string, and false indicates that it does not exist.
endsWith() returns a Boolean value, true indicates that another string exists at the end of the current string, and false indicates that it does not exist.

[Examples:

let test = "hello world";
console.log(test.includes("wo"));          // output true
console.log(test.startsWith("he"));        // output true
console.log(test.endsWith("ld"));          // output true
console.log(test.includes("helloworld"));  // output false 

 

 

 

(3) Template string (```)
Template strings are enhanced versions of strings that are identified by inverted quotes (```), can be used as normal strings, can define multiline strings, and can be embedded and parsed internally with ${}.

[Examples:

let [name, age] = ["tom", 32];
function fun() {
    return "helloworld";
}
let test2 = `${name}, 
            age = ${age - 10}, 
            say ${fun()}`;
console.log(test2);

 

 

 

5. Expansion of Objects

Expand the usage of objects.
(1) Abbreviation of attributes
ES6 allows variables to be written directly in the object, where the property is the variable name and the value of the property is the variable value.That is, {a} is equivalent to {a: a}

[Examples:

let a = "hello";
let b = {a};
console.log(b);      // output {a: "hello"}

let c = {a: a};
console.log(c);      // output {a: "hello"}

let d = {g: "hello"};
console.log(d);      // output {g: "hello"}

 

 

 

Methods in objects can also be abbreviated.

[Examples:

let [name, age] = ["tom", 32];

let person = {
    name,
    age,
    hello() {
        console.log(`${name}, ${age}`);
    },
    hello2: function() {
        console.log(`${name}, ${age}`);
    }
};

person.hello();
person.hello2();

 

 

 

(2) New method--assign()
The Object.assign() method is used for merging objects.
This implements a shallow copy, that is, if an attribute value in the source object is still an object, the copy in the target object gets a reference to that object, that is, modifying the object in the source object will affect the target object.

[Format:]
    Object.assign(target, source1, ...source2);
//Note:
    target For the target, source1, ...source2 And so on are source objects.
    //This method copies the value of the source object to the target object.
    //If an attribute with the same name appears, the latter overrides the former.
    //That is, if there is a property with the same name in target, source1, and source2, the property with the same name in the last target is source2.
    
[Examples:

let tom = {
    name: "tom",
    age: 32,
    teacher: {
        chinese: "rose",
        english: "jack"
    }
};

let jarry = {
    name: "jarry",
    age: 33,
    email: "jarry@163.com"
};

let people = Object.assign({}, tom, jarry);

console.log(people);

tom.teacher.chinese = "rick";

console.log(people);

 

 

 

How to achieve deep copy:
There is a solution: (The specific reason is not carefully explored)
Make the object a json string, and then the string an object.

Take the above example
    let people = Object.assign({}, tom, jarry);
//Change to
    let people = Object.assign({}, JSON.parse(JSON.stringify(tom)), jarry);

 

 

 

(3) New object traversal methods--keys(), values(), entries()
Object.keys() Gets the array of object keys.
Object.values() Gets the array formed by the object value.
Object.entries() gets the two-dimensional array of the object key-value.

[Examples:

let people = {
    name: "tom",
    age: 22
};

console.log(Object.keys(people));      
console.log(Object.values(people));
console.log(Object.entries(people));

 

 

 

(4) Extended operator (...)
Parameters for taking out objects and arrays and copying them into the current object.
If the data is duplicated, it will be overwritten, equivalent to Object.assign().

[Examples:

let people = {
    name: "tom",
    age: 22
};

let people2 = {
    name: "jarry",
    age: 33
};

console.log({people, people2});
console.log({...people, ...people2});


let a = [3, 1, 2];
console.log(a);
console.log(...a);

 

 

 

6. Expansion of Functions

(1) Default values of function parameters
You can specify the default value of a function while defining it and use the default value when calling if no parameters are passed.

[Examples:

function test (x, y) {
    y = y || "hello";
    console.log(x + "======" + y);
}

test("tom");                      // output tom======hello
test("tom", "helloworld");        // output tom======helloworld


function test2 (x, y = "hello") {
    console.log(x + "======" + y);
}

test2("tom");                     // output tom======hello
test2("tom", "helloworld");       // output tom======helloworld

 

 

 

(2) rest parameter
The rest parameter, in the form of a variable name, receives multiple parameters and is saved in an array.
If there are multiple parameters, rest must be at the end or an error will be reported.

[Examples:

function test (...values) {
    // for of Each time you get the value of an array
    for (let j of values) {
        console.log(j);
    }
}

test(8, 7, 9);

function test2 (...values) {
    // for in Each time an array's subscript is obtained
    for (let j in values) {
        console.log(values[j]);
    }
}
test2(8, 7, 9);

function test3 (...values, y) {            // Report errors, SyntaxError: Rest parameter must be last formal parameter
    for (let j in values) {
        console.log(values[j]);
    }
}

 

 

 

(3) Arrow function
ES6 supports defining functions using arrows=>

[Define a function using an arrow function:]

var f = v => v;
console.log(f(3));   // 3

// Equivalent to
var f = function(v){
    return v;
}
console.log(f(3)); // 3

 

 

 

If there are no parameters or there are multiple parameters, use parentheses () instead of the parameter part.
If the method body (code block) has only one statement, return can be omitted.

[Use () Substitution parameters:]

var f = () => 5;
// Equivalent to
var f = function () {
    return 5 
};


var sum = (num1, num2) => num1 + num2;
// Equivalent to
var sum = function(num1, num2) {
    return num1 + num2;
};

 

If there are multiple statements in the method body (code block), braces {} are required and return returns are used.

[Examples:

var fun = () => {
    let num = 7;
    let num2 = num + 3;
    return num + num2;
};
console.log(fun());  // 17

// Equivalent to
var fun = function() {
    let num = 7;
    let num2 = num + 3;
    return num + num2;
};
console.log(fun());   // 17

 

 

 

If an object is returned, parentheses () must be placed outside the object, otherwise {} will be parsed as a code block.

[Examples:

var getPeopleItem = id => ({ id: id, name: "Temp" });
console.log(getPeopleItem(3));   // {id: 3, name: "Temp"}

var getPeopleItem = id => { id: id, name: "Temp" };
console.log(getPeopleItem(3)); //  SyntaxError: Unexpected token :

 

 

   

Deconstruction can be used with arrow functions:

[Examples:

let people = {
    name: "tom",
    age: 22
};

let fun = (param) => {
    console.log(param.name + "==========" + param.age);
};
fun(people);

let fun2 = ({name, age}) => {
    console.log(name + "==========" + age);
};
fun2(people);

 

 

 

7. Common Array Methods

Reference: https://www.cnblogs.com/l-y-h/p/12150578.html
(1) New method--reduce()
Array.reduce(callback[, initialValue]) is used to perform a callback function on each element of an array.
Where:
The initialValue is the parameter value for the first call back execution and can be omitted.
Callback has four parameters, callback(previousValue, currentValue, index, array).
previousValue is the function value or initial value from which the callback was last executed.
CurrtValue Index Group Elements Currently Processed
index refers to the subscript of the current array element
Array refers to the current array

[Examples:

let arr = [4, 6, 5];

let newArr = arr.reduce((previousValue, currentValue, index, array) => {
    console.log("The last value processed was: " + previousValue);
    console.log("The current values processed are: " + currentValue);
    console.log("The current element subscript is: " + index);
    console.log("The current array element is: " + array[index]);
    return currentValue * 2;
});

console.log(newArr);

 

 

8. Promise Object

(1) What is Promise?
Promise is a solution for asynchronous programming.You can think of it as a container that holds the results of an operation (an asynchronous operation) that will end in the future, and the Promise object allows you to get messages about the asynchronous operation.

(2) Promise features
Feature 1: The state of the object is not affected by the outside world.
Promise has three states, Pending, Resolved, and Rejected.Only the result of the asynchronous operation can determine which state Promise is in. The rest of the operations cannot change that state and cannot cancel the operation halfway.

Feature 2: After the state changes, it will not change any more.
State changes, Pending -> Resolved, Pending -> Rejected.
Once the state changes, it will not change.

(3) Advantages of Promise
Promise cannot be cancelled, it will execute once it is created, and it cannot be cancelled halfway.
If the callback function is not set, errors inside Promise will not be thrown out.
At Pending, it is not possible to determine whether the operation is just beginning or about to be completed.

(4) How to use it?
You need to instantiate a Promise object with a new parameter of a function.
The parameters of the function are resolve and reject, and the parameters are two functions, which are provided by the JavaScript engine.
The resolve function is a state change, Pending -> Resolved, which is called after the asynchronous operation succeeds and passes the successful result of the asynchronous operation out as a parameter.
The reject function also changes state, Pending -> Rejected, which is called after an asynchronous operation fails and passes the result of the asynchronous operation as a parameter.
The then method handles the results passed by resolve and reject.It accepts two callback functions as parameters.The first callback handles the result passed by resolve, and the second handles the result passed by reject.The second callback function is optional.
In general, the catch method is used to process the results passed by reject.It is equivalent to the second callback function in the then method.

[Format:]

var promise = new Promise((resolve, reject) => {
    if(Asynchronous operation succeeded) {
        resolve(data);
    } else {
        reject(error);
    }
});

promise.then((data) => {
    // Successful operation
}).catch((error) => {
    // Failed Operation
});

 

9. Modularization

(1) What is modularization?

Modularization is about splitting code up for reuse.Similar to various jar packages in Java.
There are two main commands for modularization: export and import.
Export: Used to specify the external interface of a module, that is, the content of the module can be obtained through export.
Import: Used to import modules, that is, to establish links with other modules through import.

(2) export command
A module is usually a file whose internal variables, arrays, objects, etc., are not accessible to the outside world.You need to export it using export.
Export can export basic types of variables, functions, arrays, objects, etc.

[Export method 1:

export var test = "hello";
    
[Export mode 2:

var a = "hello";
var b = [1, 2, 3];
export {a, b};

//Export mode 1 and export mode 2 expose the interface names as variable names, function names, etc.
//Use import to fill in the correct interface name in order to reference the module properly, otherwise an error will occur.

[Export mode 3: (using as Custom Interface Name)]

var a = "hello";
var b = [1, 2, 3];
export {
    a as AA,
    b as BB
};

[Export mode 4: (using default You can ignore the interface name at this time import You can customize the interface name)]

export default {
    var a = "hello";
    var b = [1, 2, 3];
}

 

(3) import command
After export defines the module's external interface, you can use import to import the corresponding module functions.

[Import method 1: (using {} Multiple module interface names can be accepted at once)]

import {a, b} from 'xx/xx.js';

[Import method 2: (using as Name)]

import {a as AA, b as BB} from 'xx/xx.js';

[Import method three: (For export default Module, can be any name)]

import test from 'xx/xx.js';

 

To be continued

Keywords: Javascript Attribute REST JSON

Added by suomynonA on Sat, 18 Apr 2020 00:04:07 +0300