avatarfatfish

Summarize

My Boss: You Know ES6, But Why Don’t You Use It? 😠

10 complaints from my boss that helped me learn a lot.

Preface

This is how my boss roared at team members during code review meetings. The reason is his finding that many parts of the project were still using ES5. Not that ES5 is bad, there will be bugs, but it will increase the amount of code and reduce readability.

It just so happens that my boss has a habit of code cleanliness. When it comes to employees with 3 to 5 years of experience, he is extremely dissatisfied with the code of this level, and constantly complains about the code. However, I still feel that I have gained a lot from his complaints, so I decided to record the boss’ complaints and share them with you.

1. Complaints about extracting object values

Extracting attribute values is very common in programs, such as getting values from object obj.

const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  e: 5,
}
const a = obj.a
const b = obj.b
const c = obj.c
const d = obj.d
const e = obj.e
// or
const f = obj.a + obj.d
const g = obj.c + obj.e

BOSS’ complaint: Why don’t you use ES6’s destructuring assignment to get the value? Wouldn’t it be better to do it with 1 line of code?

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

I object: I don’t use ES6 because the API interface property name is not what I want.

BOSS complain: It seems that you have not mastered the destructuring 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

2. Complaints about merging data

For example, merging two arrays or merging 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}

BOSS’ complaint: Have you forgotten the ES6 spread operator, and the merging of arrays does not consider deduplication?

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. Complaints about the splicing string.

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

BOSS complain: It’s better not to use ES6 string templates as you do. You don’t know that operations can be done in ${}? We can execute arbitrary JavaScript expressions in ${}, perform operations and refer to object properties.

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

4. Complaints about using if

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

BOSS’ complaint: Wouldn’t it be better for us to use the includes method of arrays in ES6?

const condition = [ 1, 2, 3, 4 ]
if( condition.includes(type) ){
   //...
}

5. Complaints about list search.

In the project, the search function of some lists is implemented by the front-end, and the search is generally divided into two types: precise and fuzzy. Generally, we use the filter method to achieve it.

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

BOSS’ complaint: Wouldn’t you use the find method in ES6 for an exact search? Do you understand performance optimization? If a qualifying item is found in the find method, it will not continue to traverse the array.

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

6. Complaints about flat arrays.

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

const deps = {
    'department_1':[ 1, 2, 3 ],
    'department_2':[ 5, 8, 12 ],
    'department_3':[ 5, 14, 79 ],
    'department_4':[ 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)]

BOSS’ complaint: Do I need to traverse to get all the property values of the object? You forgot about Object.values? Why not use the flat method provided by ES6?

const deps = {
    'department_1':[ 1, 2, 3 ],
    'department_2':[ 5, 8, 12 ],
    'department_3':[ 5, 14, 79 ],
    'department_4':[ 3, 64, 105 ],
}
let member = Object.values(deps).flat(Infinity)

Remarks: Infinity is used as the parameter of flat, so that we do not need to know the dimensions of the flattened array.

7. Complaints about getting object attribute values.

const name = obj && obj.name

BOSS’ complaint: Won’t you use the optional chain operator in ES6?

const name = obj?.name

8. Complaints about adding object properties.

When we add properties to an object, what should we do if the property names change dynamically?

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

BOSS’ complaint: Why create an extra variable. Don’t you know that object property names in ES6 can use expressions?

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

9. Complaints about non-empty judgment

When processing user input, it is often judged whether the input box has been input.

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

BOSS’ complaint: Have you heard about the new null value coalescing operator in ES6, do you have to write so many conditions?

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

10. Complaints about asynchronous functions

Asynchronous functions are common and are often implemented as promises.

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

BOSS’ complaint: If you use asynchronous functions like this, you are not afraid to form a callback hell!

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

Finally

You are welcome to try and refute the above 10 BOSS complaints. If your refutation is reasonable, I will refute it for you at the next code review meeting.

This article’s translation has been authorized by the original author (Hong chenlianxin).

The original address is https://juejin.cn/post/7016520448204603423

Thank you for reading.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.

Front End Development
JavaScript
Programming
Web Development
Software Development
Recommended from ReadMedium