1. If statements with multiple conditions

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

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['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.

// Longhand let test: boolean; if (x > 100) { test = true; } else { test = false; } // Shorthand let test = (x > 10) ? true : false; // Let 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 than 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.

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

5. Null check and default assignment

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

6. Undefined check and default assignment

let test1 = undefined, test2 = test1 || ''; console.log("undefined check", test2); / / output ""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); // Output: "default" const test1 = 0?? 2; console.log(test1); // 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.

// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
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.

// Longhand if (test1 === true) or if (test1 ! == "") or if (test1 ! If (test1) {// type (type);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.

// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (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] = 32
Copy the code

12. Return after comparison

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

// Longhand let test; function checkReturn() { if (! (test === undefined)) { return test; } else { return callMe('test'); } } var data = checkReturn(); console.log(data); //output test function callMe(val) { console.log(val); } // Shorthand function 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.

// Longhand
function 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.

// Longhand
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // ...
}
// Shorthand
var 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.

//longhand
function calculate(diameter) {
  return Math.PI * diameter
}
//shorthand
calculate = diameter => (
  Math.PI * diameter;
)
Copy the code

17. Exponential representation

// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) {
Copy the code

18. Default parameter values

//Longhand function add(test1, test2) { if (test1 === undefined) test1 = 1; if (test2 === undefined) test2 = 2; return test1 + test2; } //shorthand add = (test1 = 1, test2 = 2) => (test1 + test2); Add () // Output: 3Copy the code

19. Extension operator simplification

Const data = [1, 2, 3]; const test = [4 ,5 , 6].concat(data); // type type of sleep per minute; // type of sleep per minute; 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.

Const test1 = [1, 2, 3]; Const 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.

//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
//shorthand
const welcome = `Hi ${test1} ${test2}`;
Copy the code

21. Cross-line strings

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

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

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

//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { 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];
        }
    }
}
//Shorthand
filteredData = 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?

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

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.

//longhand if(arr.indexOf(item) > -1) { // item found } if(arr.indexOf(item) === -1) { // item not found } //shorthand if(~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 requires! ~. Alternatively, you can use the include() function.

If (arr.includes(item)) {// True if the item is 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

// Longhand Math.floor(1.9) === 1 // true // Sleep ~~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]; // c
Copy the code

34. Exponential power simplification

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

— — — — — — — — — — — — — —

Later encountered to complement again ~~~~