Front end development ES6

Keywords: Javascript Front-end

         It is recommended that front-end developers use ES6 for development, which can reduce the amount of code and increase readability.

1. About value

const obj = {
    a:1,
    b:2,
    c:3,
    d:4,
    e:5,
}

Make complaints:

const a = obj.a;
const b = obj.b;
const c = obj.c;
const d = obj.d;
const e = obj.e;

perhaps

const f = obj.a + obj.d;
const g = obj.c + obj.e;

Tucao: "do you not use ES6's deconstruction assignment to get values? Do you use 5 lines of code to make complaints about 1 lines? Use object names and attribute names to fix values. If object names are short, they are long, and the code is full of the object name."

improvement:

const {a,b,c,d,e} = obj;
const f = a + d;
const g = c + e;

refute

Instead of using the deconstruction assignment of ES6, the attribute name in the data object returned by the server is not what I want. For this value, I don't have to re create a traversal assignment.

Make complaints

It seems that you have not mastered the deconstruction assignment of ES6 thoroughly. If the variable name you want to create is inconsistent with the property name of the object, you can write this:

const {a:a1} = obj;
console.log(a1);// 1

supplement

The deconstruction assignment of ES6 is easy to use. Note, however, that 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.

const {a,b,c,d,e} = obj || {};

2. Merge data  

For example, merge two arrays and two objects.

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

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

Make complaints

Has the extension operator of ES6 been forgotten, and the merging of arrays does not consider de duplication?

improvement

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

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

  3. Splice string

const name = 'Xiao Ming';
const score = 59;
let result = '';
if(score > 60){
  result = `${name}I passed the exam`; 
}else{
  result = `${name}I failed in the exam`; 
}

Make complaints

It's better not to use ES6 string template like you do. You don't know what you can do in ${}. You can put any JavaScript expression in ${}, perform operations, and reference object properties.

improvement

const name = 'Xiao Ming';
const score = 59;
const result = `${name}${score > 60?'I passed the exam':'I failed in the exam'}`;

  4. Judgment condition in if

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

Make complaints

Will the array instance method includes be used in ES6?

improvement

const condition = [1,2,3,4];

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

  5. List search

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.

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

Make complaints

If it is an accurate search, won't find in ES6 be used? Performance optimization understand? If you find a qualified item in the find method, you won't continue to traverse the array.

improvement

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

6. Flattened array

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.

const 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 item in deps){
    const value = deps[item];
    if(Array.isArray(value)){
        member = [...member,...value]
    }
}
member = [...new Set(member)]

Make complaints

Do you want to traverse to get all the attribute values of the object? Have you forgotten Object.values? 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?

improvement

const 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.

supplement

The flat method does not support IE browser.

7. Get object property value

const name = obj && obj.name;

Make complaints

Will the optional chain operators in ES6 be used?

improvement

const 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 = `topic${index}`;
obj[key] = 'Topic content';

Make complaints

Why create an extra variable. Do you know that the object attribute name in ES6 can be expressed?

improvement

let obj = {};
let index = 1;
obj[`topic${index}`] = 'Topic content';

  9. Judgment of non empty input box

When processing the business related to the input box, we often judge the scenario where no value is entered in the input box.

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

Make complaints

Have you understood the new null value merging operator in ES6 and written so many conditions?

if(value??'' !== ''){
  //...
}

10. Make complaints about asynchronous functions.

Asynchronous functions are very common and are often implemented with Promise.

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

Make complaints

If you call an asynchronous function like this, you are not afraid to form a hell callback!

improvement

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

supplement

However, Promise.all() is still used for concurrent requests.

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

In case of concurrent requests, as long as one of the asynchronous functions completes processing, the result will be returned. Promise.race() is used.

 

Posted by predhtz on Mon, 29 Nov 2021 08:07:23 -0800