This article mainly refers to Ruan yifong’s introduction to ECMAScript 6, omits the concept introduction of each chapter, and summarizes how to optimize code with the new ES6 syntax.
Not finished, updated……
1, spread operator spread (…) The use of
Copy an array
// const arrCopy = [...arr] const [...arrCopy] = arrCopy the code
Convert a string to an array
[...'Hello']
Copy the code
2. Use rest parameters
Instead of arguments inside a function
The rest parameter cannot be followed by any other parameter; otherwise, an error will be reported
// In strict mode, Arguments // Bad instance function foo() {const args = array. from(arguments) return args. Join (")} // good instance function foo(... args) { return args.join('') }Copy the code
3. Use default syntax to set function parameters
// bad instance
function bar(opt) {
opt = opt || {}
}
// good instance
function bar(opt = {}) {
}
Copy the code
4. Eliminate magic strings using Symbol
A magic string is a specific string or number that occurs multiple times in the code and is strongly coupled to the code
// The following "Triangle" is the magic string // "Triangle" occurs many times, forming a "strong coupling" with the code, which is not good for future modification and maintenance. function getArea(shape, {width, height}) { let area = 0; Switch (shape) {case 'Triangle': area = 0 * width * height; break; / /... } return area; } getArea('Triangle', {width: 100, height: 50});Copy the code
1. Write shapeType as triangle property to eliminate coupling; It doesn’t matter what the triangle value of shapeType is, just make sure it doesn’t conflict with the triangle value of other shapeType properties
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 the code
5, use (? .). The link determination operator determines whether an object exists
ES2020 introduces (? .). . In the chain call,? Check whether the object on the left exists. If it does, go down. If it does not, 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 the code
Reference books
es6.ruanyifeng.com/