The original address

Quote: Atit front end craftsman

Developers are always learning new things, and it shouldn’t be harder to keep up with these technological changes than it was before.

Hopefully this will make my code a little bit cleaner

1. If statements with multiple conditions

Place multiple values in an array and call the includes method of the array.

//longhandif (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {    //logic}//shorthandif (['abc', 'def', 'ghi', 'jkl'].includes(x)) {   //logic}
Copy the code

2. Simplify if true… else

For if-else conditions that do not contain large logic, you can use the following shortcut. We can achieve this simplification simply by using the ternary operator.

// Longhandlet test: boolean; if (x > 100) { test = true; } else { test = false; }// Shorthandlet test = (x > 10) ? true : false; //or we can use directlylet test = x > 10; console.log(test);Copy the code

You can do this if you have nested conditions.

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

3. Declare variables

We use this shorthand when we want to declare two variables that have the same value or the same type.

//Longhand let test1; let test2 = 1; //Shorthand let test1, test2 = 1;Copy the code

4. Check null, undefined, and null values

When we create a new variable, we sometimes want to check that the referenced variable is not null or undefined. JavaScript does have a nice shortcut for this kind of checking.

// Longhandif (test1 ! == null || test1 ! == undefined || test1 ! == '') { let test2 = test1; }// Shorthandlet test2 = test1 || '';Copy the code

5. Null check and default assignment

let test1 = null, test2 = test1 || ''; console.log("null check", test2); // output will be ""Copy the code

6. Undefined check and default assignment

let test1 = undefined, test2 = test1 || ''; console.log("undefined check", test2); // output will be ""Copy the code

General value check

let test1 = 'test', test2 = test1 || ''; console.log(test2); // output: 'test'Copy the code

In addition, for points 4, 5 and 6 above, you can use?? Operators.

If the left-hand value is null or undefined, the right-hand value is returned. By default, it returns the value on the left.

const test= null ?? 'default'; console.log(test); // expected output: "default"const test1 = 0 ?? 2; console.log(test1); // expected output: 0Copy the code

7. Assign values to multiple variables

This technique is useful when we want to assign values to multiple different variables.

//Longhand let test1, test2, test3; test1 = 1; test2 = 2; test3 = 3; //Shorthand let [test1, test2, test3] = [1, 2, 3];Copy the code

8. Handy assignment operators

In programming, we deal with a large number of arithmetic operators. This is one of the useful tricks for JavaScript variable assignment operators.

// Longhandtest1 = test1 + 1; test2 = test2 - 1; test3 = test3 * 20; // Shorthandtest1++; test2--; test3 *= 20;Copy the code

9. If Check whether the value exists

This is a common, easy technique that we all use, and it’s still worth mentioning here.

// Longhandif (test1 === true) or if (test1 ! == "") or if (test1 ! == null)// Shorthand //it will check empty string,null and undefined tooif (test1)Copy the code

Note: If test1 has a value, the logic after if is performed. This operator is mainly used for null or undefinded checks.

10. The && operator for multiple criteria

If the function is called only when the variable is true, use the && operator.

//Longhand if (test1) { callMethod(); } //Shorthand test1 && callMethod();
Copy the code

11. For each loop

This is a common loop simplification technique.

// Longhandfor (var i = 0; i < testData.length; i++)// Shorthandfor (let i in testData) or  for (let i of testData)
Copy the code

Iterate over each variable in the array.

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

12. Return after comparison

We can also use comparisons in return statements, which reduce five lines of code to one.

// Longhandlet test; function checkReturn() { if (! (test === undefined)) { return test; } else { return callMe('test'); }}var data = checkReturn(); console.log(data); //output testfunction callMe(val) { console.log(val); }// Shorthandfunction checkReturn() { return test || callMe('test'); }Copy the code

Arrow function

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

More examples:

function callMe(name) { console.log('Hello', name); }callMe = name => console.log('Hello', name);Copy the code

14. Short function calls

We can use the ternary operator to implement multiple function calls.

// Longhandfunction test1() { console.log('test1'); }; function test2() { console.log('test2'); }; var test3 = 1; if (test3 == 1) { test1(); } else { test2(); }// Shorthand(test3 === 1? test1:test2)();Copy the code

15. The switch simplified

We can store conditions in key-value objects and invoke them based on conditions.

// Longhandswitch (data) { case 1: test1(); break; case 2: test2(); break; case 3: test(); break; // And so on... }// Shorthandvar data = { 1: test1, 2: test2, 3: test}; data[something] && data[something]();Copy the code

16. Implicit return

By using the arrow function, we can return the value directly without a return statement.

//longhandfunction calculate(diameter) {  return Math.PI * diameter}//shorthandcalculate = diameter => (  Math.PI * diameter;)
Copy the code

17. Exponential representation

// Longhandfor (var i = 0; i < 10000; i++) { ... }// Shorthandfor (var i = 0; i < 1e4; i++) {
Copy the code

18. Default parameter values

//Longhandfunction add(test1, test2) { if (test1 === undefined) test1 = 1; if (test2 === undefined) test2 = 2; return test1 + test2; }//shorthandadd = (test1 = 1, test2 = 2) => (test1 + test2); add() //output: 3Copy the code

19. Extension operator simplification

//longhand// joining arrays using concatconst data = [1, 2, 3]; const test = [4 ,5 , 6].concat(data); //shorthand// joining arraysconst data = [1, 2, 3]; const test = [4 ,5 , 6, ...data]; console.log(test); // [4, 5, 6, 1, 2, 3]Copy the code

We can also clone using the extended operator.

//longhand// cloning arraysconst test1 = [1, 2, 3]; const test2 = test1.slice()//shorthand// cloning arraysconst test1 = [1, 2, 3]; const test2 = [...test1];Copy the code

20. Template literals

If you’re tired of using + to concatenate multiple variables into a single string, this simplification trick will be a headache free.

//longhandconst welcome = 'Hi ' + test1 + ' ' + test2 + '.'//shorthandconst welcome = `Hi ${test1} ${test2}`;
Copy the code

21. Cross-line strings

We can do this when dealing with cross-line strings in our code.

//longhandconst data = 'abc abc abc abc abc abc\n\t'    + 'test test,test test test test\n\t'//shorthandconst data = `abc abc abc abc abc abc         test test,test test test test`
Copy the code

22. Object attribute assignment

let test1 = 'a'; let test2 = 'b'; //Longhand let obj = {test1: test1, test2: test2}; //Shorthand let obj = {test1, test2};Copy the code

23. Convert strings into numbers

//Longhand let test1 = parseInt('123'); Let test2 = parseFloat (' 12.3 '); //Shorthand let test1 = +'123'; Let test2 = + '12.3';Copy the code

24. Deconstruct assignment

//longhandconst test1 = this.data.test1; const test2 = this.data.test2; const test2 = this.data.test3; //shorthandconst { test1, test2, test3 } = this.data;Copy the code

25. Array find simplification

The find method is useful when we have an array of objects and want to find specific objects based on their properties.

const data = [{ type: 'test1', name: 'abc' }, { type: 'test2', name: 'cde' }, { type: 'test1', name: 'fgh' },]function findtest1(name) { for (let i = 0; i < data.length; ++i) { if (data[i].type === 'test1' && data[i].name === name) { return data[i]; } }}//ShorthandfilteredData = data.find(data => data.type === 'test1' && data.name === 'fgh'); console.log(filteredData); // { type: 'test1', name: 'fgh' }Copy the code

26. Conditional lookup simplification

If we want to call different methods based on different types, we can use multiple else if statements or switches, but is there a better simplification technique?

// Longhandif (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); }// Shorthandvar types = { test1: test1, test2: test2, test3: test3, test4: test4}; var func = types[type]; (! func) && throw new Error('Invalid value ' + type); func();Copy the code

27. Bitwise manipulation of indexOf is simplified

When looking for a value in an array, we can use the indexOf() method. But there’s a better way. Let’s look at this example.

//longhandif(arr.indexOf(item) > -1) { // item found }if(arr.indexOf(item) === -1) { // item not found}//shorthandif(~arr.indexOf(item)) { // item found}if(! ~arr.indexOf(item)) { // item not found}Copy the code

The bitwise () operator returns true (except -1), and the reverse operation only needs to be done! . Alternatively, you can use the include() function.

if (arr.includes(item)) { // true if the item found}
Copy the code

28. Object.entries()

This method converts an object to an array of objects.

const data = { test1: 'abc', test2: 'cde', test3: 'efg' }; const arr = Object.entries(data); console.log(arr); /** Output:[ [ 'test1', 'abc' ], [ 'test2', 'cde' ], [ 'test3', 'efg' ]]**/Copy the code

29. Object.values()

This is also a new feature introduced in ES8 and functions like Object.entries(), but without the keys.

const data = { test1: 'abc', test2: 'cde' }; const arr = Object.values(data); console.log(arr); /** Output:[ 'abc', 'cde']**/Copy the code

30. Double bitwise operation

// LongHandmath.floor (1.9) === 1 // true// Awakened ~~1.9 === 1 // trueCopy the code

31. Repeat string multiple times

We can use a for loop to repeatedly manipulate the same character, but there is an easier way.

//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

Find the maximum and minimum value of the array

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

33. Get the character of the string

let str = 'abc'; //Longhand str.charAt(2); // c//Shorthand str[2]; // cCopy the code

34. Exponential power simplification

/ / longhandMath pow (2, 3); // 8//shorthand2**3 // 8Copy the code