The purpose of this paper

  • πŸ˜ƒ How to make your code look more elegant
  • πŸ₯° makes code more readable and intuitive
  • πŸ‘ Avoid useless code and reduce the amount of code
  • πŸ‚πŸ”₯ When your colleagues see your code, they are so impressed that they call it a pro

Use && instead of if

const doSometions = () = > {}

const isTrue = true
let temp = ' '
if(isTrue){
    doSometings()
    temp = 'isTrue'
}

// Alternatives
isTrue && this.doSometings()
isTrue && (temp == 'isTrue')
Copy the code

Switch to replace the if

const temp = 1

if(temp === 1) {// ...
}
if(temp === 2) {// ...
}

// Alternatives
switch(true) {case temp === 1:
        // ...
        break;
    case temp === 2:
        // ...
        break;
    default:
        // ...
        break;
}
Copy the code

[] or {} => null (never trust data returned from the back end)

const { data } = await getApiData()

// If data is an array
console.log(data[0]) // If data returns null, an error is reported

// If data type is an object
console.log(data.a) // If data returns null, an error is reported

// Can be written as follows
console.log((data || [])[0])
console.log((data || {}).a)
// If data returns null, undefined will be displayed, and no error will be reported blocking code
Copy the code

Generates an array of length N

// Generate an array of length 100
const arrN = [...Array(100).keys()]
/ / [0,1,2,3,..., 99]
Copy the code

Generates an array from A to Z

const AZCodeArr = [...Array(91).keys()].filter(i= > i > 64).map(i= > String.fromCharCode(i))
//['A','B','C','D'...]
Copy the code

Take the last digit

const num = 12345
const num2 = '54321'
console.log(num%10) / / 5
console.log(num2%10) // 1 Implicit conversions are also possible
Copy the code

integer

const num = 123.456
console.log(num | 0) / / 123
Copy the code

Write a middleware to manage your utility classes

// index.js

[
  'utilA'.'utilB'
].forEach(m= > {
  Object.assign(exports.require(`./lib/${m}`))})exports.lodash = require('lodash')

Object.defineProperty(exports.'installedBrowsers', {
  enumerable: true,
  get () {
    return exports.getInstalledBrowsers()
  }
})

// External references
const { utilA, utilB, lodash: _} =require('utils')
Copy the code

At the end

This article will always be updated!

⏲⏲⏲ Updated at 2021-12-11

πŸ‘πŸ‘πŸ‘ feel useful can collect use!!

❀️❀️❀️ thanks for reading, little friends feel good click a like!!