Optimize ES5 grammar using ES6 grammar, welcome to add

Keywords: Javascript Front-end

ES6 is recommended for program optimization and aesthetics. (All javaScript syntax after ES5 is collectively referred to as ES6)

1. About Value Selection

Values are common in programs, such as obj from an object.

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;

Typhoon: "Won't you use ES6's deconstruction assignment to get values? Five lines of code do not work well with one line of code? Use object name plus attribute name directly to get values. If the object name is short, it's good. It's got this object name all over the code."

Improvement:

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

refute

Instead of using the ES6 deconstruction assignment, the attribute names in the data objects returned by the server side are not what I want, so to get the value, it is not necessary to recreate the traversal assignment.

Make complaints

It seems that you don't have a thorough understanding of the deconstruction assignment of ES6. If the variable name you want to create does not match the object's property name, you can write as follows:

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

supplement

Destructive assignment for ES6 is useful. Note, however, that the decomposed object cannot be undefined, null. Otherwise, an error will be reported, so a default value will be given to the decomposed object.

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

2. About merging 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 obj2 = {
  b:1,
}
const obj = Object.assign({}, obj1, obj2);//{a:1,b:1}

Make complaints

Has the extended operator for ES6 been forgotten, and are there any merges of arrays that are not considered redundant?

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. About Stitching Strings

const name = 'Xiao Ming';
const score = 59;
let result = '';
if(score > 60){
  result = `${name}Test Results Passed`; 
}else{
  result = `${name}Failed the exam`; 
}

Make complaints

If you use an ES6 string template like yours, you don't know what you can do in ${} at all. 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?'Test Results Passed':'Failed the exam'}`;

4. On the Judgment Conditions in if

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

Make complaints

Will the array instance method includes in ES6 be used?

Improvement

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

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

5. About List Search

In a project, the search function of some non-paged lists is implemented by the front end, which is generally divided into exact search and fuzzy search. Search is also called filtering, which is usually done with a filter.

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

Make complaints

Wouldn't Find in ES6 be used for precise search? Understand performance optimization, if you find a qualifying item in the find method, you won't continue traversing the array.

Improvement

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

6. About Flattened Arrays

In a department JSON data, the attribute name is the Department id, and the attribute value is an array collection of department member ids. Now you need to extract all the department member IDS into an array collection.

const deps = {
'Purchasing Department':[1,2,3],
'Ministry of Personnel':[5,8,12],
'Administrative 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 I have to traverse to get all the property values of the object? Did Object.values forget? There is also flattening of arrays. Why not use the flat method provided by ES6? Fortunately, the depth of the array can only be 2-dimensional at most, but also 4- and 5-Dimensional arrays. Should we have to cycle nested loops to flatten them?

Improvement

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

Infinity is used as a flat parameter so that the dimensions of the flattened array are unknown.

supplement

The flat method does not support IE browsers.

7. About Getting Object Attribute Values

const name = obj && obj.name;

Make complaints

Will the optional chain operator in ES6 be used?

Improvement

const name = obj?.name;

8. About adding object attributes

When adding attributes to an object, what happens 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? Don't know if the object property name in ES6 is an expression available?

Improvement

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

9. Judgment on Input Box Not Empty

When dealing with business related to input boxes, it is common to judge scenarios where input boxes do not have input values.

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

Make complaints

Did you know about the new null value merge operator in ES6? Do you want to write so many conditions?

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

10. About Asynchronous Functions

Asynchronous functions are 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're not afraid of a Hell callback.

Improvement

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

supplement

But Promise.all() is still used when making concurrent requests.

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

If concurrent requests are made, the result is returned as long as one of the asynchronous functions is processed, using Promise.race().

11. About variable declarations

ES6 recommends using let to declare local variables, as opposed to var (where it is declared, it is considered declared at the top of the function)
The difference between let and var declarations:

var x = 'global variable';
{
  let x = 'local variable';
  console.log(x); // local variable
}
console.log(x); // global variable

let denotes declared variables, while const denotes declared constants, both of which are block-level scopes; Variables declared by const are considered constant, meaning that their values cannot be modified once they are set:

const a = 1
a = 0 //Report errors

If const is an object, the value contained in the object can be modified. To be abstract, the address the object points to is not changed:

const student = { name: 'cc' }

student.name = 'yy';// No error
student  = { name: 'yy' };// Report errors

12. About for...of and for...in

for...of is used to iterate over an iterator, such as an array:

let letters = ['a', 'b', 'c'];
letters.size = 3;
for (let letter of letters) {
  console.log(letter);
}
// Results: a, b, c

for...in is used to traverse attributes in an object:

let stus = ["Sam", "22", "male"];
 for (let stu in stus) {
   console.log(stus[stu]);
  }
// Result: Sam, 22, Male

13. Follow-up

In addition, the errors in the above collation are welcome to make corrections in the comments. Thank you very much.

If you have other people who want to spit, you are also welcome to leave your slot in the comments.

It's helpful to finish reading, so you might want to pay attention and give some support.

Posted by geoldr on Sun, 05 Dec 2021 19:25:26 -0800