Summary of 9 common ES6 features (these are generally enough)

ECMAScript 6.0 (hereinafter referred to as ES6) is the next generation standard of JavaScript language, which has been officially released in June 2015. Its goal is to make JavaScript language can be used to write complex large-scale applications and become an enterprise development language. ES6 has brought us many unexpected functions. Here, let's learn about 9 super practical ES6 features.

1. Expand operator

As the name suggests, the expansion operator (...) used before an object or array expands a structure into a list. Demonstrate:

let firstHalf = [  one ,  two ];let secondHalf = [ three ,  four , ...firstHalf];

Is this writing elegant and concise enough? If you don't need to expand the operator
We have to write:

let firstHalf = [  one ,  two ];let secondHalf = [ three ,  four ];for(var i=0, i <firstHalf.length; i++ ) {  secondHalf.push(firstHalf[i]);}

The expand operator also applies to the properties of merged objects:

const hero = {  name:  Xena - Warrior Princess ,  realName:  Lucy Lawless}const heroWithSword = { ...hero, weapon:  sword}

If you do not need to expand the operator, you need to traverse the properties of the object:

let keys = Object.keys(hero);let obj = {};
for(var i=0; i< keys.length; i++) {   obj[keys[i]] = keys[props[i]];}

2. Residual parameters

The remaining parameters will be included in the data series. The characteristic of JavaScript is that the number of parameters is very flexible. There is usually an arguments variable to collect parameters. Let's take an example:

function add(first, second, ...remaining) {  return first + second;}

The above code only adds first and second, that is, calling add (1,2) and add (1,2,3,4) will get the same result.
Let's amend it:

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

As mentioned earlier,... Remaining collects the remaining parameters and provides us with the naming of these parameters, which clearly indicates that we intend to deal with the remaining parameters. I remember that there are arguments in ES5 at the latest, but few people know.

3. String interpolation

Have you ever seen such a statement?

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 }}

Of course, I'm referring to the unreadable multi statement in the getDescription() method. A similar phenomenon exists in most programming languages. Some 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}   `;}

You can use ${} interpolation in a pair of wrapped strings. It looks much more comfortable now.

4. Abbreviated attribute

It must be written in ES5:

function createCoord(x, y) {  return {    x: x,    y: y  }}

Short attributes can be used after ES6:

function createCoord(x, y) {  return {    x,    y  }}

Does it look fresher?

5. Method properties

A method property is a property that points to a method defined in an object. Consider the following section of 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; }}

6. Deconstruction assignment

Deconstruction assignment is beneficial to the mental health of the developer himself. 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)}

No matter from what point of view, the above code is not perfect, but it does reflect an application scenario. We want to obtain data from different levels of objects. You might ask, what's the problem here? Well, I can save some keystrokes without 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)

Look, our code above compresses three lines into one line.
Deconstruction assignment is not limited to objects. It also applies to arrays. Consider the following code:

const array = [1,2,3,4,5,6];const a = array[0];const c = array[2];

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

const array = [1,2,3,4,5,6];const [a, ,c, ...remaining] = arr;
// remaining = [4,5,6]

We can use the above pattern matching to decompose the values of the array. We use, skip some values. The remaining parameters mentioned above can also be used here. Here, we capture the remaining array members through the remaining parameters.
Deconstruction assignments can also be used for functions and parameters. When a function has more than 2-3 parameters, using an object to collect all parameters is the de facto standard of JavaScript. For example, the following function:

function doSomething(config) {  if(config.a) { ... }  if(config.b) { ... }  if(config.c) { ... }}

There is a better way to write:

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

7. Array method

ES6 introduces many useful array methods, such as:

  • find(), find the members in the list, and return null, indicating that they are not found
  • findIndex(), find the index of the list member
  • some() to check whether an assertion is true on at least one member of the list
  • includes, whether the list contains an item

The following code will help 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) // 1arr.some(item => item.checked) // true
const numberArray = [1,2,3,4];numberArray.includes(2) // truePromises + Async/Await

8. Asynchronous scheme

If you have been in this circle for some years, you may remember that there was a time when we only had callback, 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. Later, we had the promise library and people began to use 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 call in this way to string promise:

getUser()  .then(getOrderByUser)  .then(getOrderItemsByOrder)  .then(orderItems => {    // Process sorted members})

Later, we had a better life
The above code can be written as follows:

async function getItems() {  try {    const user = await getUser();    const order = await getOrderByUser(user);    const items = await getOrderItemsByOrder(order);    return items;  } catch(err) {    // To handle errors here, it is recommended to return a certain value or re throw the error}
getItems().then(items => {  // Process sorted members}

9. Module

Almost any programming language supports the concept of module, that is, the code is divided into multiple files, and each file 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.jsimport mult, { add, sub } from  ./math ;
mult(2, 4) // 8add(1,1)   // 2sub(1,2)   // -1

We use the export keyword to indicate the two structures of add and sub, which are publicly visible to any module that introduces the module. The export default keyword indicates the structure obtained only when importing the module. In main JS, we name the imported default mult, and indicate that we introduce add() and sub(). Arrow function and dictionary scope this.

Click follow to learn about Huawei's new cloud technology for the first time~

Tags: Javascript Programming ECMAScript Programmer Huawei Cloud

Posted by Gambler on Wed, 25 May 2022 00:25:11 +0300