A lot of people have five years of JavaScript experience, but the reality is they’ve only used it five times in one year. Some people can write spaghetti code with the same logic and functionality, while others can write two or three lines of clean code. Clean code is not only easy to read, it also reduces the likelihood of complex logic and errors. This article introduces some common JavaScript simplification techniques that you can use in your daily development.

1. Simplify conditional expressions

It is often the case that regular logical expressions to determine whether a variable is a specified value can be very long. What I did was put the values in an array:

/ / too long logical expression the if (x = = = 'ABC' | | x = = = 'def' | | x = = = 'ghi' | | x = = = 'JKL') {/ / other logic} / / short if ([' ABC 'and' def ', 'ghi, 'JKL '].includes(x)) {// other logic}Copy the code

2. If… else

if… Else is so common that many people forget that there are other ways to judge conditions. For simple variable assignments, there is no need for such a long statement.

// let test= Boolean; if (x > 100) { test = true; } else { test = false; } // Let test = (x > 10)? true : false; // Let test = x > 10; console.log(test);Copy the code

Ternary expressions can do complex conditional branching at the expense of readability:

let x = 300,
let test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"

Copy the code

3. Null and assign the default value

In Code Review I often see Code like this: if the variable is not null, undefined “, assign to the second variable, otherwise give the default value:

if (first ! == null || first ! == undefined || first ! == '') { let second = first; } / / short let second = first | | '.Copy the code

4. Short loop traversal

The for loop is basic, but a little tedious. Can be used for… In, for… Instead of or forEach:

// Longhand
for (var i = 0; i < testData.length; i++)

// Shorthand
for (let i in testData) or  for (let i of testData)

Copy the code

Array traversal:

function testData(element, index, array) { console.log('test[' + index + '] = ' + element); } [11, 24, 32].forEach(testData); // Prints: test[0] = 11, test[1] = 24, test[2] = 32Copy the code

4. Simplify the switch

This technique is also commonly used to convert the switch to the key-value form of the object. The code is much cleaner:

// Longhand
switch (data) {
  case 1:
    test1();
  break;

  case 2:
    test2();
  break;

  case 3:
    test();
  break;
  // And so on...
}

// Shorthand
var data = {
  1: test1,
  2: test2,
  3: test
};

data[anything] && data[anything]();

Copy the code

5. Simplify multi-line string concatenation

If a string expression is too long, we might split it into multi-line concatenation. But with the popularity of ES6, it’s better to use template strings:

//longhand
const data = 'abc abc abc abc abc abc\n\t'
    + 'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
         test test,test test test test`

Copy the code

6. Use arrow functions to simplify returns

The arrow function in ES6 is a nice thing. It works best when the function is simple enough to return an expression without writing:

Longhand:
//longhand
function getArea(diameter) {
  return Math.PI * diameter
}
//shorthand
getArea = diameter => (
  Math.PI * diameter;
)

Copy the code

7. Simplify branch condition statements

It’s you again, if… else if… The else! Similar to switch, it can be simplified in key-value form:

// Longhand if (type === 'test1') { test1(); } else if (type === 'test2') { test2(); } else if (type === 'test3') { test3(); } else if (type === 'test4') { test4(); } else { throw new Error('Invalid value ' + type); } // Shorthand var types = { test1: test1, test2: test2, test3: test3, test4: test4 }; var func = types[type]; (! func) && throw new Error('Invalid value ' + type); func();Copy the code

8. Repeat the string N times

Sometimes a string needs to be repeated N times for some purpose, and the stupidest way is to concatenate it with a for loop. Actually, the simpler way is to repeat:

//longhand 
let test = ''; 
for(let i = 0; i < 5; i ++) { 
  test += 'test '; 
} 
console.log(str); // test test test test test 
//shorthand 
'test '.repeat(5);

Copy the code

9. Exponential operation

/ / longhand math.h pow (2, 3); // 8 //shorthand 2**3 // 8Copy the code

10. Numeric delimiters

This is a relatively new syntax, introduced in ES2021. Large numbers can be separated by underscores when written, which improves readability:

// 旧语法
let number = 98234567

// 新语法
let number = 98_234_567

Copy the code

conclusion

There’s nothing to summarize. Just use it.

In this paper, starting from the public, mp.weixin.qq.com/s/rc7eGREVP…