As the name implies, the expansion operator used before an object or array (…) To expand a structure into a list.

To demonstrate:

let firstHalf = [ one , two ];

let secondHalf = [ three , four , …firstHalf];

Is this elegant enough, concise enough? If you don’t expand the operator

We have to write this:

let firstHalf = [ one , two ];

let secondHalf = [ three , four ];

for(var i=0, i <firstHalf.length; i++ ) {

secondHalf.push(firstHalf[i]);

}

The expansion operator also applies to merging objects’ properties:

const hero = {

name: Xena – Warrior Princess ,

realName: Lucy Lawless

}

const heroWithSword = {

. hero,

weapon: sword

}

Instead of expanding the operator, we iterate over the object’s properties:

let keys = Object.keys(hero);

let obj = {};

for(var i=0; i< keys.length; i++) {

obj[keys[i]] = keys[props[i]];

}

2. Remaining parameters

The remaining parameters add the remaining parameters to the sequence. The nature of JavaScript is that the number of parameters is flexible. There is usually a arguments variable to collect the arguments.

Let’s look at an example:

function add(first, second, … remaining) {

return first + second;

}

The above code simply adds first and second, that is, calling add(1, 2) and add(1, 2, 3, 4) will get the same result.

Let’s fix it:

function add(first, second, … remaining) {

return first + second + remaining.reduce((acc, curr) => acc + curr, 0); }

As mentioned above… Remaining collects the remaining parameters and gives us their names, making it clear that we intend to process the remaining parameters. I remember arguments as late as ES5, but few people know about it.

3. String interpolation

Have you ever seen a statement like this?

class Product {

constructor(name, description, price) {

this.name = name;

this.description = description;

this.price = price;

}

getDescription() {

return ” Full description

“+

” name: ” + this.name +

” description: ” + this.description

}

}

I’m referring, of course, to the unreadable multi-line statement in the getDescription() method. A similar phenomenon exists in most programming languages. Several languages provide string interpolation, and fortunately JavaScript is one of them.

Let’s rewrite the getDescription() method:

getDescription() {

return Full description : name: ${this.name} description ${this.description} ; }

A pair of wrapped strings can be interpolated with ${}. It looks much more comfortable now.

4. Shorthand properties

In ES5 you must write:

function createCoord(x, y) {

return { x: x, y: y }

}

ES6 can use abbreviated properties later:

function createCoord(x, y) {

return { x, y } }

Does it look fresher?

Method properties are properties that point to a method defined in an object.

Consider the following ES5 code as an example:

const math = {

add: function(a,b) { return a + b; },

sub: function(a,b) { return a – b; },

multiply: function(a,b) { return a * b; }

}

After ES6, just write:

const math = {

add(a,b) { return a + b; },

sub(a,b) { return a – b; },

multiply(a,b) { return a * b; }

}

5. Deconstruct assignment

Deconstructing assignment is good for the developer’s own mental health.

Consider the following code:

function handle(req, res) {

const name = req.body.name;

const description = req.body.description;

const url = req.url;

log( url endpoint , url);

// A lot of code logic

dbService.createPerson(name, description)

}

The code above isn’t perfect by any stretch of the imagination, but it does represent a scenario where we want to fetch data from different levels of an object. You might ask, what’s the problem here? Well, I can save myself a few keystrokes by not declaring so many variables.

function handle(req, res) {

const { body: { name, description }, url } = req;

log( url endpoint , url);

// A lot of code logic

dbService.createPerson(name, description)

See, our code above compresses three lines into one.

Deconstructing assignment is not limited to objects. It also applies to arrays.

Consider the following code:

Const array = [6];

const a = array[0];

const c = array[2];

The above code can be rewritten in a more elegant way:

Const array = [6];

const [a, ,c, …remaining] = arr;

/ / remaining = (4 and 6)

We can use the pattern matching above to decompose the values of the array. We use,, to skip some values. The remaining parameters mentioned above can also be used here, where we use the remaining parameters to capture the remaining array members.

Destructuring assignments can also be used for functions and parameters. When a function has more than 2-3 parameters, it is a JavaScript de facto standard to use a single object to collect all of them.

For example, the following function:

function doSomething(config) {

if(config.a) { … }

if(config.b) { … }

if(config.c) { … }} there are better ways to write:

function doSomething({ a, b, c }) {

if(a) { … }

if(b) { … }

if(c) { … }}

7. Array methods

ES6 introduces many useful array methods, such as:

Find (), find a member of the list, return null to indicate that findIndex() was not found, find some(), check if an assertion is true on at least one member of the list, and check if the list contains an item. The following code helps you understand their usage:

const array = [{ id: 1, checked: true }, { id: 2 }];

arr.find(item => item.id === 2) // { id: 2 }

arr.findIndex(item => item.id === 2) // 1

arr.some(item => item.checked) // true

Const numberArray = [1, 2, 3, 4];

numberArray.includes(2) // true

Promises + Async/Await

8. Asynchronous scheme

If you’ve been around for a while, you may remember a time when all we had was a pullback

Something like this:

function doSomething(cb) {

setTimeout(() => { cb( done ) }, 3000) }

doSomething((arg) => { console.log( done here , arg); })

We use callbacks because some operations are asynchronous and take time to complete. Then we had the Promise library, and people started using it. Then JavaScript gradually added native support for Promise.

function doSomething() {

return new Promise((resolve, reject) => { setTimeout(() => { resolve( done ) }, 3000) }) }

doSomething().then(arg => {

console.log( done here , arg); })

We can even string promises together like this:

getUser()

.then(getOrderByUser)

.then(getOrderItemsByOrder)

.then(orderItems => {

// Process sorted membersCopy the code

})

Then life gets better and we have async/await

The above code could be written like this:

async function getItems() {

try {

const user = await getUser();

const order = await getOrderByUser(user);
Copy the code

const items = await getOrderItemsByOrder(order);

return items;

} catch(err) {

// Handle errors here. It is recommended to return a value or rethrow an error

}

}

getItems().then(items => {

// Process sorted members}

9, modules,

Almost any programming language supports the concept of modules, which divide code into files, each of which is a self-contained unit (module).

Consider the following code:

// math.js

export function add(a,b) { return a + b; }

export function sub(a,b) { return a – b; }

export default mult(a,b) => a * b;

// main.js

import mult, { add, sub } from ./math ;

mult(2, 4) // 8

Add (1, 1) / / 2

Sub (1, 2) / / 1

We noted the add and sub structures above with the export keyword, which are publicly visible to any module that introduces the module. The export default keyword indicates the structure obtained when only importing modules. In main.js, we name the imported default mult and specify that we introduce the add() and sub() methods. Arrow function and dictionary scope this.