The use of advanced features in the language can help us implement complex functions, make the code look more concise and logical with as few statements as possible, and thus reduce the risk of bugs. Let me summarize a few JavaScript shorthand tips.

1. Declare multiple variables

// let x; let y = 20; // let x, y = 20;Copy the code

2. Assign values to multiple variables

We can use arrays to deconstruct assignments and assign multiple variables in a single line of code.

// let a, b, c; a = 5; b = 8; c = 12; // let [a, b, c] = [5, 8, 12];Copy the code

3. Use ternary operators appropriately

We can save 5 lines of code here with the ternary operator (also known as the conditional operator).

// let marks = 26; let result; if(marks >= 30){ result = 'Pass'; }else{ result = 'Fail'; } let result = marks >= 30? 'Pass' : 'Fail';Copy the code

4. Specify the default value

We can use the “OR (| |) short circuit is evaluated” logic, given a default value. When | | our expectations is a “false” value, the entire value of the expression will pick up to our given default values.

// let imagePath; let path = getImagePath(); if(path ! == null && path ! == undefined && path ! == '') { imagePath = path; } else { imagePath = 'default.jpg'; } / / short let imagePath = getImagePath () | | 'default. JPG';Copy the code

5. AND(&&) short-circuit evaluation

If you only call a function if a variable is true, you can use “AND(&&) short-circuit evaluation” logic instead.

// If (isLoggedin) {goToHomepage(); } // isLoggedin && goToHomepage();Copy the code

When you want to conditionally render a component, try using the AND(&&) abbreviation. Take the following example

<div> { this.state.isLoading && <Loading /> } </div>
Copy the code

6. Swap the values of two variables

When we want to swap the values of two variables, we often introduce a third variable. In fact, we can easily swap two variables by array destructuring assignment.

let x = 'Hello', y = 55; // Add a third variable const temp = x; x = y; y = temp; [x, y] = [y, x];Copy the code

7. Use arrow functions

Function add(num1, num2) {return num1 + num2; } const add = (num1, num2) => num1 + num2;Copy the code

8. Template string

We usually use the + operator to concatenate strings with other types of variables. With ES6 template strings, we can combine strings in a much simpler way.

Console. log('You got a missed call from '+ number +' at '+ time); Console. log(' You got a missed call from ${number} at ${time} ');Copy the code

9. Multi-line strings

For multi-line strings, we usually implement a concatenation of the + operator with a new line break (\n). We can make this easier by using backquotes (‘).

// Console. log('JavaScript, often abbreviated as JS, is a\n' + 'programming language that conforms to the \n' + 'ECMAScript specification. JavaScript is high-level,\n' + 'often just-in-time compiled, and multi-paradigm.' ); // Abbreviated console.log(' JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm.`);Copy the code

10. Multiple condition checks

For multi-value matching, we can put all values in an array, using the indexOf() or includes() methods provided by the array as shorthand.

/ / regular writing the if (value = = = 1 | | value = = = 'one' | | value = = = 2 | | value = = = 'two') perform some code} {/ / / / short 1 if ([1, 'one, two, 'two'] indexOf (value) > = 0) perform some code} {/ / / / short 2 if ([1, 'one', 2, 'two']. Includes (value)) {} / / execute some codeCopy the code

11. Object attribute allocation

If the variable name is the same as the attribute name of the object, then we can write only the variable name in the object, instead of writing both the attribute name and the attribute value (the value of the variable). JavaScript automatically sets the property name to be the same as the variable name and assigns the property value to the variable value.

let firstname = 'Amitav'; let lastname = 'Mishra'; // let obj = {firstname: firstname, lastname: lastname}; Let obj = {firstname, lastname};Copy the code

12. Converting a String to a Number

There are built-in methods, such as parseInt and parseFloat, that convert strings to numbers. We can also do this by simply providing a unary operator + in front of the string value.

// let total = parseInt('453'); Let business = parseFloat (' 42.6 '); // let total = +'453'; Let business = + '42.6';Copy the code

13. Repeat a string multiple times

To repeat a string a specified number of times, you can use the for loop. But with the repeat() method, we can do it on a single line.

// 常规写法
let str = ''; 
for(let i = 0; i < 5; i ++) { 
  str += 'Hello '; 
} 
console.log(str); // Hello Hello Hello Hello Hello 

// 简写
'Hello '.repeat(5);
Copy the code

14. Power of the power

We can use the math.pow () method to power a number. A more concise syntax is the double star (**).

// const power = math.pow (4, 3); // Const power = math.pow (4, 3); // 64 // const power = 4**3; / / 64Copy the code

15. Double NOT operator (~~)?

The two-not operator (~~) is an alternative to the math.floor () method.

// const floor = math.floor (6.8); // 6 // const floor = ~~6.8; / / 6Copy the code

Note: The two-not operator method only works with 32-bit integers, i.e. (2^31) -1=2147483647. So for any number greater than 2147483647, the bit operator (~~) gives an incorrect result, so math.floor () is recommended in this case.

16. Find the maximum and minimum values in the array

We can use the for loop to iterate through a set of numbers to find a maximum or minimum value. You can also use the array.reduce () method to find the maximum and minimum values in an Array.

But using the expansion operator (…) We can, we can implement this requirement in one line of code.

// const arr = [2, 8, 15, 4]; Math.max(... arr); // Max. 15 math.min (... arr); // Minimum value 2Copy the code

17. For loops

To iterate through an array, we usually use the traditional for loop. We can use for… To iterate over an array. To access the index of each value of the array, we can use for… In circulation.

let arr = [10, 20, 30, 40]; 

// 常规写法,for循环
for (let i = 0; i < arr.length; i++) { 
  console.log(arr[i]); 
} 

// 简写

// for...of循环
for (const val of arr) { 
  console.log(val); 
} 

// for...in循环
for (const index in arr) { 
  console.log(`index: ${index} and value: ${arr[index]}`); 
}
Copy the code

We can also use for… The in loop iterates through the properties of the object.

let obj = {x: 20, y: 50}; 
for (const key in obj) { 
  console.log(obj[key]); 
}
Copy the code

18. Merge arrays

let arr1 = [20, 30]; // let arr2 = arr1.concat([60, 80]); / / [20, 30, 60, 80] / / short let arr2 = [... arr1, 60, 80]; // [20, 30, 60, 80]Copy the code

19. Deep copies of multi-level objects

To make a deep copy of a multi-level object, we can iterate through each of its properties to see if the current property contains an object. If so, the same function is recursively called and the current property value (the nested object) is passed in as an argument to the function.

If our object does not contain function, undefined, NaN, or Date equivalents, we can also do this using json.stringify () and json.parse ().

If our object is a single layer object, that is, there are no nested objects, then we can also use the expansion operator (…) Deep copy.

let obj = {x: 20, y: {z: 30}}; Const makeDeepClone = (obj) => {let newObject = {}; Object.keys(obj).map(key => { if(typeof obj[key] === 'object'){ newObject[key] = makeDeepClone(obj[key]); } else { newObject[key] = obj[key]; }}); return newObject; } const cloneObj = makeDeepClone(obj); Const cloneObj = json.parse (json.stringify (obj)); // Const cloneObj = json.parse (json.stringify (obj)); // Short for single-layer objects (no nested objects) let obj = {x: 20, y: 'hello'}; const cloneObj = {... obj};Copy the code

20. Get a character in a string

let str = 'jscurious.com'; CharAt (2); // c // short STR [2]; // cCopy the code

More programming skills please pay attention to the public account “Space programming”