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.
- Reduced conditional expression
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}
- Simplify the if… else
if… Else is so common that many people forget that there are other ways to judge conditions. Let test= Boolean; // Let test= Boolean; if (x > 100) { test = true; } else { test = false; } // Let test = (x > 10)? true : false; // Let test = x > 10; console.log(test);
Triadic 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”
- Null and assign default values
In Code Review I often see Code that assigns the second variable if it is not null, undefined “, otherwise it defaults to if (first! == null || first ! == undefined || first ! == ”) { let second = first; } / / short let second = first | | ‘.
- Short for loop traversal
The for loop is basic, but a little tedious. Can be used for… In, for… // Longhand for (var I = 0; i < testData.length; i++)
// Shorthand for (let i in testData) or for (let i of testData)
Function testData(Element, index, array) {console.log(‘test[‘ + index + ‘] = ‘+ element); }
[11, 24, 32].forEach(testData); // Prints: test[0] = 11, test[1] = 24, test[2] = 32
- To simplify the switch
// 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] && dataanything;
- Simplified 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
- Use arrow functions to simplify returns
The arrow function in ES6 is a nice thing. It works best when the function is as simple as returning an expression, and you don’t even need to write: Longhand: //longhand function getArea(diameter) { return Math.PI * diameter } //shorthand getArea = diameter => ( Math.PI * diameter; )
- Simplified branch condition statements
It’s you again, if… else if… The else! // 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();
- 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. 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);
- Index of operation
Can save the province, low carbon environmental protection. / / longhand math.h pow (2, 3); // 8 //shorthand 2**3 // 8
- Numeric separator
// Let number = 98234567 // let number = 98234567
// Let number = 98_234_567