7 code optimization tips every front-end should master

1. Automatic matching of strings ( Array.includes)

We often encounter such a requirement when writing code, we need to check whether a certain string is one of the strings that meet our requirements. The most common way is to use ||and ===to judge the match. But if we use this judgment method extensively, it will definitely make our code very bloated and very tiring to write. In fact, we can use it Array.includesto help us automatically match.

// 未优化前的写法
const isConform = (letter) => {
    
     
if (letter === "a" ||letter === "b" ||letter === "c" ||
   letter === "d" || letter === "e") {
    
    
   return true;   
}   
return false; };

```javascript
// 优化后的写法
 const isConform = (letter) =>   ["a", "b", "c", "d", "e"].includes(letter);

2. for-ofAnd for-inautomatic traversal

for-ofAnd for-in, can help us to automatically traverse each element in the sum, without requiring us to manually change the index to traverse the elements Array.object

Note: We recommend that objects ( object) use for-intraversal, and arrays ( Array) use for-oftraversal

for-of

const arr = ['a',' b', 'c'];
 // 未优化前的写法 
for (let i = 0; i < arr.length; i++) {
    
    
   const element = arr[i]; 
   console.log(element);
}
// 优化后的写法 
for (const element of arr) {
    
    
    console.log(element);
} 
// expected output: "a" // expected output: "b" // expected output: "c"

for-in

const obj = {
    
       a: 1,   b: 2,   c: 3, };
 // 未优化前的写法 
 const keys = Object.keys(obj); 
 for (let i = 0; i < keys.length; i++) {
    
    
    const key = keys[i];   
    const value = obj[key];   
    // ... }

js

copy code

// 优化后的写法 for (const key in obj) { const value = obj[key]; // ... }

3. false judgment

If you want to judge whether a variable is null、undefined、0、false、NaN、'', you can use logical not ( !) to invert to help us judge, instead of using every value ===to judge

// 未优化前的写法 
const isFalsey = (value) => {
    
     
if (value === null ||value === undefined ||
   value === 0 || value === false ||value === NaN ||value === "") {
    
     
return true;  
 }  
return false; };
// 优化后的写法
 const isFalsey = (value) => !value;

4. Ternary operator instead of ( if/else)

We must have encountered a selection structure when we were writing code if/else, and the ternary operator can be regarded as if/elsea kind of syntactic sugar, which can be expressed more concisely if/else.

// 未优化前的写法 let info; 
if (value < minValue) {
    
    
   info = "Value is最小值";
 } else if (value > maxValue) {
    
    
    info = "Value is最大值"; 
 } else {
    
    
    info = "Value 在最大与最小之间";
 }
//优化后的写法
 const info =   value < minValue   ? "Value is最小值"  : value > maxValue ? "Value is最大值" : "在最大与最小之间";

5. Selection of function calls

The ternary operator can also help us determine which function should be called in the current situation.

function f1() {
    
    
   // ... 
} 
function f2() {
    
    
   // ... 
 } 
 // 未优化前的写法 
if (condition) {
    
     
   f1(); }
else
{
    
    
f2(); 
}
// 优化后的写法 
(condition ? f1 : f2)();

6. Use objects instead of switch/case selection structures

switch caseUsually there is a casevalue corresponding to a return value, such a structure is similar to our object, and a key corresponds to a value. switch/caseWe can replace our selection structure with our object , making the code more concise

const dayNumber = new Date().getDay(); 
// 未优化前的写法
 let day; switch (dayNumber) {
    
       
 case 0:    
  day = "Sunday";    
   break;   
   case 1:     
   day = "Monday";     
   break;   
   case 2:    
    day = "Tuesday";    
     break;   case 3:    
     day = "Wednesday";    
     break;   case 4:   
       day = "Thursday";   
         break; 
           case 5:    
          day = "Friday";   
           break;  
            case 6:   
              day = "Saturday"; }
// 优化后的写法
 const days = {
    
       
 0: "Sunday",  
  1: "Monday",   
  2: "Tuesday",   
  3: "Wednesday",  
   4: "Thursday",   
   5: "Friday",   
   6: "Saturday", 
   };
  const day = days[dayNumber];`

7. ||The use of logic or ( )

If we want to obtain a value that is not sure whether it exists, we often use the if judgment to judge whether the value exists before obtaining it. If it doesn't exist we return another value. We can use the logic or ( ||) feature to optimize our code

// 未优化前的写法 
let name; 
if (user?.name) 
{
    
       
name = user.name; 
} else {
    
    
   name = "Anonymous";
}
// 优化后的写法
 const name = user?.name || "Anonymous";

Guess you like

Origin blog.csdn.net/weixin_45506717/article/details/130811160