ECMAScript 6 (ES6 for short) is a JavaScript language standard officially released in June 2015. Given the amount of new content, I’ve compiled some useful and common ES6 features that I can learn to get started
let/const
The let command is used to declare variables. Its use is similar to var, but the declared variable is only valid within the code block in which the let command resides. The const command is used to declare a constant. Once a constant is declared, its value cannot be changed. It must be initialized immediately and cannot be assigned later. This syntax effectively compensates for the shortcomings of the var keyword (variable promotion, polluting global variables, etc.)
The statement | scope | Initialize the |
---|---|---|
let | Within the code block | no |
const | Within the code block | is |
var | It is also accessible outside the code block | no |
The following code declares two variables, let and var, respectively, in the code block. These two variables are then called outside of the code block, with the let variable reporting an error and the var variable returning the correct value.
{ let x = 0; var y = 0; const i; } console.log(x); / / error console. The log (y); // The correct valueCopy the code
Template string
If you’ve ever experienced the hassle of concatenating HTML with quotation marks and plus signs. Well, template strings can solve this problem by simply concatenating variables directly with ${XXX} and back single quotes
const template = `<div>
<span>${text}</span>
</div>`
Copy the code
Arrow function
ES6 allows functions to be defined using arrows (=>)
const test = ()=> {}
Copy the code
Arrow functions have the following characteristics for functions created using the traditional function keyword:
- You do not need the function keyword to create functions
- Omit the return keyword
- Inherits the this keyword from the current context
The method of deconstructing assignment of variables
An array of
let a = 1; let b = 2; let c = 3; Equivalent to let [a, b, c] = [1, 2, 3]; Let [a = 1] = []; let [a = 1] = []; Destruct assignment can also specify a default value when destruct === undefined is required
object
let { a, b } = { a: 1, b: 2 }; Similar to an array structure, this is used to get specific methods of an object, such as let {log, sin, cos} = Math;
Var {a: newName} = {a: ‘aaa’, b: ‘BBB’}; The colon “:” looks for the variable assigned to “:” by the value of the object before “:” in the object after “=”
string
let [a, b, c, d, e] = 'hello';
a="h" b="e" c="l" d="l" e="o"
Copy the code
Function parameters
Can be used to assign parameters to functions
function add([x, y]){ return x + y; } add([1, 2]); / / 3Copy the code
You can also set the default value
function move({x = 0, y = 0} = {}) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, 0] move({}); // [0, 0] move(); / / [0, 0]Copy the code
use
- Swap the values of variables
let x = 1; let y = 2; [x, y] = [y, x];
- The definition of function arguments, especially if default values are used, can be reduced
var a = x || 0;
This kind of statement
function test({x, y, z}) { ... }
test({z: 3, y: 2, x: 1});
Copy the code
- Local reference module
const { SourceMapConsumer, SourceNode } = require("source-map");
Promise to optimize asynchronous code
ES6 is a big killer for asynchronous schemes. The original traditional asynchronous callback method becomes more and more heavy with the big WEB era, and the callback hell appears, which is extremely elegant in coding and viewing.
By creating a function Promise object with parameters resolve and Reject, once the two functions are executed, the Promise will transition from the PEDding state and be called into the chained callback THEN or catch.
new Promise((resolve, reject)=> {
setTimeout(()=> {
resolve(111);
}, 1000);
})
.then(res=> {
console.log(res);
})
.catch(()=> {})
Copy the code
If you return a new Promise in then or catch, you can implement an infinitely long chained callback to solve callback hell.
new Promise((resolve, reject)=> {
setTimeout(()=> {
resolve();
}, 1000);
})
.then(()=> {
return new Promise((resolve, reject)=>{
resolve(111)
})
})
.then(res=> {
console.log(res);
})
Copy the code
In addition to addressing callback issues, the promise.all and promise.race methods are provided to provide an efficient solution for handling concurrent requests. In a track and field event, “ALL” means that the results are announced after all the runners finish the race, while “race” means that the results are announced as soon as the first runner finishes the race.
The promise.all () method takes an array of Promise items and ultimately returns a Promise object. When all promises in this array change from pedding state, the returned Promise object will be resolved or reject. That means we can use then and catch catches from returning Promise objects.
Promise.all([p1,p2,p3]).then(res=> {
console.log(res);
})
Copy the code
The promise.race () method also takes an array of Promise items and ultimately returns a Promise object. Once a Promise in this array changes from pedding state, the returned Promise object will immediately be resolved or reject.
Promise.race([p1,p2,p3]).then(res=> {
console.log(res);
})
Copy the code