Optimizing code with ES6

Increase 2021-09-15 10:51:52

The content of the article mainly refers to the work of Ruan Yifeng great God ECMAScript 6 introduction , Omit the concept introduction of each chapter , Summarize the use of ES6 How the new syntax optimizes the code .

unfinished , Updating ......

1、 Extension operator spread(...) Use

Copy an array

// Writing a
const arrCopy = [...arr]
// Write two
const [...arrCopy] = arr
 Copy code 

Convert string to array

[...'Hello']
 Copy code 

2、rest Use of parameters

In place of function body arguments

rest Parameters cannot be followed by any other parameters , Otherwise, an error will be reported

// In strict mode , No use arguments
// bad instance
function foo() {
const args = Array.from(arguments)
return args.join('')
}
// good instance
function foo(...args) {
return args.join('')
}
 Copy code 

3、 Use the default value syntax to set the parameters of the function

// bad instance
function bar(opt) {
opt = opt || {}
}
// good instance
function bar(opt = {}) {
}
 Copy code 

4、 Use Symbol Eliminate magic strings

The magic string refers to , Multiple occurrences in code , A specific string or value that forms a strong coupling with the code

// Below “Triangle” It's the magic string
// "Triangle" Multiple occurrences , And code formation “ Strong coupling ”, Not conducive to future modification and maintenance .
function getArea(shape, {width, height}) {
let area = 0;
switch(shape) {
case 'Triangle':
area = 0.5 * width * height;
break;
// ...
}
return area;
}
getArea('Triangle', {width: 100, height: 50});
 Copy code 

Revised as follows : 1、 It's written in shapeType Of triangle attribute , Eliminate coupling ; 2、shapeType Of triangle It doesn't matter what the value of the attribute equals , Just make sure you don't interact with others shapeType If the attribute values of are in conflict , It's very suitable for Symbol value

const shapeType = {
triangle: Symbol()
}
function getArea(shape, {width, height}) {
let area = 0;
switch(shape) {
case shapeType.triangle:
area = 0.5 * width * height;
break;
// ...
}
return area;
}
 Copy code 

5、 Use (?.) The link determination operator determines whether the object exists

ES2020 Introduced (?.). In the chain call ,?. Determine whether the object on the left exists , Existence goes on , non-existent , return undefined.

// bad
const firstName = message.body.user.firstName || 'default'
// good
const firstName = (
message
&& message.body
&& message.body.user
&& message.body.user.firstName) || 'default'
// best
const firstName = message?.body?.user?.firstName || 'default'
 Copy code 

Reference books

es6.ruanyifeng.com/

Please bring the original link to reprint ,thank
Similar articles

2021-09-15

2021-09-15