ES6 you understand, but can you really use it? (here are 10 points to test whether you have been recruited)

Posted by Matth_S on Sun, 02 Jan 2022 17:27:53 +0100

preface

The following is a summary of some ES6 knowledge points commonly used in my development, which does not represent all. It should be noted that the js syntax after ES5 is collectively referred to as ES6 (naming ES7, es8, etc. is nonstandard).

1. Deconstruction assignment

In a program, we often take value operations, such as taking value from an object obj

let obj = {
    a:1,
    b:2,
    c:3
}

ES5 value

let a = obj.a;
let b = obj.b;
let c = obj.c;

In the above value selection method, it's better to have fewer attributes. If there are many attributes, the amount of code will increase a lot, which seems redundant and cumbersome.

If you know how to use the deconstruction assignment of ES6, the writing method is as follows

let {a,b,c} = obj;

The original multi line code is now completed in one line of code. Isn't it fragrant? Especially when the object name is very long or there are many attributes, this method can greatly simplify the code and improve the cleanliness and development efficiency.

However, in one case, the attribute name in the data object returned by the server is not what I want. In this way, do I have to re create a traversal assignment? Of course not. There is a way to write deconstruction assignment, which can perfectly solve this problem

let {a:a1,b,c} = obj;

// At this point, it is equivalent to getting attribute a and changing it to the desired attribute name a1
console.log(a1)

Note: Although the deconstruction assignment of ES6 is easy to use, the deconstructed object cannot be undefined or null, otherwise an error will be reported, so a default value should be given to the deconstructed object

let {a,b,c} = obj || {};

2. Extended operator (...)

For example, merge two arrays or two objects (multiple)

ES5 writing method

let a = [1,2,3];
let b = [1,5,6];
let c = a.concat(b);   // [1,2,3,1,5,6]

let obj1 = {
  a:1
}
let obj2 = {
  b:1
}
let obj = Object.assign({}, obj1, obj2);    // {a:1,b:1}

In this case, the ES6 extension operator (...) is used directly Combined with Set, it is simple and easy to remove weight directly. Isn't it wonderful?

let a = [1,2,3];
let b = [1,5,6];
let c = [...new Set([...a, ...b])];   // [1,2,3,5,6]

let obj1 = {
  a:1
}
let obj2 = {
  b:1
}
let obj = {...obj1,...obj2};   // {a:1,b:1}

3. Template string

Maybe you can already use template strings, similar to

let name = 'leo';
let score = 66;
let result = '';
if(score > 60){
  result = `${name}You passed the exam with a score of ${score}`; 
}else{
  result = `${name}Your test result is unqualified, with a score of ${score}`; 
}
console.log(result);   // leo passed with a score of 66

However, have you ever known that ${} can do more than that. You can put any JavaScript expression in ${}, perform operations, and reference object properties

let name = 'leo';
let score = 66;
let result = `${name}${score > 60 ? 'I passed the exam' : 'I failed in the exam'}`;  //There is an expression in ${}

4,includes

In multi conditional if judgment statements, the conventional writing method may be

if(type == 1 || type == 2 || type == 3 || type == 4){
   //...
}

At first glance, it seems a little cumbersome. Imagine that if there are dozens or even more judgment conditions, should they be listed one by one?

This dilemma can be avoided by using the ES6 array instance method include

let conditionList = [1,2,3,4];

if(conditionList.includes(type)){
   //...
}

5,find

In the project, the search function of some non paged lists is realized by the front end. The search is generally divided into accurate search and fuzzy search. Search is also called filtering, which is generally implemented by filter

let a = [1,2,3,4,5];
let result = a.filter(item =>{
    return item === 3
})

The above method can be implemented, but it is not the best, because even if the items that meet the conditions are filtered, all the items of the array are still traversed

Using ES6 find can exit the traversal after finding the items that meet the conditions, which is helpful for performance optimization

let a = [1,2,3,4,5];
let result = a.find(item =>{
    return item === 3
})

6,Object.values and flat

In the JSON data of a department, the attribute name is the Department id, and the attribute value is an array set of department member IDs. Now we need to extract the member IDs of departments into an array set

let deps = {
    'Purchasing Department':[1,2,3],
    'Ministry of Personnel':[5,8,12],
    'Administration Department':[5,14,79],
    'Ministry of transport':[3,64,105],
}
let member = [];
for (let key in deps){
    let value = deps[key];
    if(Array.isArray(value)){
        member = [...member,...value]
    }
}
member = [...new Set(member)]

Do you want to traverse to get all the attribute values of the object? Object.values forgot? It also involves the flattening of arrays. Why not use the flat method provided by ES6? Fortunately, the depth of the array this time is only 2 dimensions at most, and it is also necessary to encounter 4-dimensional and 5-Dimensional arrays. Do you have to loop nested loops to flatten?

ES6 optimization

let deps = {
    'Purchasing Department':[1,2,3],
    'Ministry of Personnel':[5,8,12],
    'Administration Department':[5,14,79],
    'Ministry of transport':[3,64,105],
}
let member = Object.values(deps).flat(Infinity);

Infinity is used as the parameter of flat, so that there is no need to know the dimension of the flattened array.

Note: the flat method does not support IE browser.

7. Optional chain operator

To obtain the properties of an object, the general practice can be

let name = obj && obj.name;

Use the ES6 optional chain operator , allows you to read the value of an attribute deep in the chain of connected objects without explicitly verifying that each reference in the chain is valid

let name = obj?.name;

8. Add object properties

When adding an attribute to an object, what should I do if the attribute name changes dynamically?

let obj = {};
let index = 1;
let key = `name${index}`;
obj[key] = 'leo';

If you create a variable in the above way, do you know that the object attribute name in ES6 can be expressed?

let obj = {};
let index = 1;
obj[`name${index}`] = 'leo';   // With the template string, the object property name uses an expression

// Or obj [` ${'name' + index} `] ='leo ', the expression is used in the template string

9. Null value merge operator??

When dealing with the business related to the input box, you will often judge the scene where the value is not entered in the input box. You may be familiar with the following code

if (value !== null && value !== undefined && value !== ''){
    //...
}

When you know the null value merge operator in ES6, you can write it like this

if ((value??'') !== ''){   // If the value of value is null or undefined, the value on the left () takes?? Right ''
  //...
}

10. Promise and async await

Asynchronous functions are very common and are often implemented with Promise

let fn1 = () =>{
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1);
    }, 500);
  });
}
let fn2 = () =>{
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(2);
    }, 1000);
  });
}
let fn = () =>{
   fn1().then(res1 =>{
      console.log(res1);   // 1
      fn2().then(res2 =>{
        console.log(res2)   // 2
      })
   })
}

fn()

Calling asynchronous functions in this way is easy to form callback purgatory. async await can be used for optimization

let fn = async () => {
  let res1 = await fn1();
  let res2 = await fn2();
  console.log(res1);   // 1
  console.log(res2);   // 2
}

fn()

Promise. Com can be used when concurrent requests are required all()

let fn = () =>{
   Promise.all([fn1(),fn2()]).then(res =>{
       console.log(res);   // [1,2]
   }) 
}

fn()

When concurrent requests are made, promise. Com is required if one of the asynchronous functions returns results after processing race()

let fn = () =>{
   Promise.race([fn1(),fn2()]).then(res =>{
       console.log(res);   // 1
   })
}

fn()

extend

ES6 arrow function

Detailed introduction to Js arrow function (have you learned the differences of various use scenarios?)_ CSDN blog - a brief understanding of the arrow function is a specification added in ES6, which simplifies the writing of anonymous function definitions. Basic format complete writing let FN = (x, y) = > {return x + y;}// Function() writing let FN = function (x, y) {return x + y;} () can be omitted if there is only 1 parameter. / / () let FN = x = > {return x + X;}// Function() write let FN = functionhttps://blog.csdn.net/qq_41809113/article/details/122003373?spm=1001.2014.3001.5502

Topics: Javascript Front-end ECMAScript