A clean piece of code will not only make you feel better, it will also make your code more compelling. A great product needs to be polished bit by bit to stand out, and lean code is an important part of that. So, let’s take a look at some common ways to optimize code.

1. Multiple conditions judgment

The array includes method is used to determine whether an element is included, returning true if it is, false otherwise.

// longhand
if (student === "Tom" || student === "Jack" || student === "Shanguagua") {
  // business
}
 
// shorthand
if (['Tom', 'Jack', 'Shanguagua'].includes(student)) {
  // business
}
Copy the code

2, If true… The else abbreviations

Simple comparative logic can be written this way. If the business in charge of such writing, code readability will be poor, the next day is probably afraid to admit that they wrote.

// longhand let win; let score = 70; if (score > 100) { win = true; } else { win = false; } // shorthand let win = (score > 100) ? true : false; Let win = score > 100;Copy the code

Ternary operators are also a good choice, but more than two criteria are less beautiful.

let win = (score > 90) ? 'A' (score > 80) : 'B'

Declare variables

Try this if you need to declare two variables that have the same value or type.

//Longhand 
let Tom = 1;
let Jack = 1;
 
//Shorthand
let Tom, Jack = 1;
Copy the code

4. Null and undefined checks

Sometimes we need to check whether null or undefined values are referenced.

// Longhand if (Tom ! == null || TomTom ! == undefined || test1 ! == '') { let Mick = Tom; } // Shorthand let Mick = Tom || '';Copy the code

5. Null checking and assigning defaults

If we want to assign B to variable A, and if B is false, we assign some value to A.

let A = null,
    B = A || '';
Copy the code

| | operators is short circuit or operation, known as the reason of the short circuit operation, if the first operand is true, will not judge the second operand, because no matter why the second operand, the final result must be true. Am& is called short-circuiting because when the first operand is false, the second operand will not be judged because the final result must be false regardless of what the second operand is.

6. Multiple variable assignments

This method is useful when we need to assign different values to different variables, and the beauty of the code is most evident.

// Longhand 
var Tom, Jack, Shanguagaua;
Tom = 'A';
Jack = 'B';
Shanguagaua = 'C';
 
// Shorthand 
let [Tom, Jack, Shanguagau] = ['A', 'B', 'C'];
Copy the code

7. Multiple conditional AND (&&) operators

If is one way to perform other operations on true, but the AND operator is a bit higher.

// Longhand 
if (ready) {
    goToEat(); 
} 
 
// Shorthand 
ready && goToEat();
Copy the code

Arrow function

Arrow functions are an ES6 feature that simplifies function writing, among other features.

//Longhand 
function GoToEat(a, b) { 
    return a + b; 
 } 
 
 //Shorthand 
 const GoToEat = (a, b) => a + b;
Copy the code

Short function calls

Judge the calls of two functions based on conditions.

// Longhand
function A() {
  console.log("A");
}
function B() {
  console.log("B");
}
 
var c = 5;
if (c == 10) {
  A();
} else {
  B();
}
 
// Shorthand
(c === 1 ? A : B)();
Copy the code

10. Switch Shorthand

Judge multiple function calls based on conditions.

// Longhand
switch (key) {
    case 1:
      A();
    break;
    case 2:
      B();
    break;
    case 3:
      C();
    break;
    // And so on...
  }
  
  // Shorthand
  var data = {
    1: A,
    2: B,
    3: C
  };
  
  data[something] && data[something]();
Copy the code

Because a value that doesn’t exist in an object gets a false value, AND a true value, combined with the AND operator.

11. Default parameter values

By taking advantage of the default value feature of a function, you can avoid validating false values.

//Longhand
function GoToEat(A, B) {
  if (A === undefined) A = 1;
  if (B === undefined) B = 2;
  return A + B;
}
 
//shorthand
GoToEat = (A = 1, B = 2) => A + B;
GoToEat(); // output: 3
Copy the code

12. Dot operators

Concatenation of arrays can be done using dot operators.

//Longhand const A = [1, 2, 3]; const B = [4, 5, 6].concat(A); // Shorthand const A = [1, 2, 3]; const B = [4, 5, 6, ...A]; // [4, 5, 6, 1, 2, 3]Copy the code

Of course, you can copy an array using the dot operator, note the deep copy.

// Longhand
var A = [1, 2, 3];
var B = A.slice();
 
//shorthand
var A = [1, 2, 3];
var B = [...A];
Copy the code

13, array. find

The find method is really useful when we have an array of objects and we want to look up specific objects based on object properties, which is a common operation for data filtering.

// Longhand
const data = [
  {
    type: "student",
    name: "Tom",
  },
  {
    type: "teacher",
    name: "Mick",
  },
  {
    type: "student",
    name: "Shanguagua",
  },
];
function findStudent(name) {
  for (let i = 0; i < data.length; ++i) {
    if (data[i].type === "student" && data[i].name === name) {
      return data[i];
    }
  }
}
 
//Shorthand
filterdData = data.find(
  (data) => data.type === "student" && data.name === "Shanguagua"
); // { type: 'student', name: 'Shanguagua' }
Copy the code

Repeat a string multiple times

To repeat the same characters over and over again, we can use the for loop and add them to the same loop. There is always a concise way to write repeated operations.

// Longhand 
let Tom = ''; 
for(let i = 0; i < 5; i ++) { 
  Tom += 'Tom '; 
} 
console.log(str); // Tom Tom Tom Tom Tom 
 
// Shorthand 
'Tom '.repeat(5); // Tom Tom Tom Tom Tom 
Copy the code

15. Find the maximum and minimum values in the array

At first glance, uh, for loop, oh, no.

const arr = [1, 2, 3]; Math. Max (... arr); / / 3 Math. Min (... arr); / / 1Copy the code

In terms of front-end video, you can pay attention to my B station and search for “Braising beans is not boring”. There are videos uploaded from front-end entry to mastery (1000 big collection), zero-based play on wechat mini program, correct posture of using Webview in 5G era, etc., looking forward to interaction with you on B station oh!