By Amitav Mishra

Translator: Awkward and romantic

20 JavaScript Techniques that will Save your time

Personal translation, reprint please indicate the source

If you like, you can pay attention to my new public account “front-end see outside”, and update 1~2 foreign technical articles translated by yourself every week

Are there any problems or errors with this article that you are welcome to point out in the comments

The shorthand techniques of any programming language help you to write more clean and optimized code and lets you Achieve your goal with less coding. Let’s discuss some of the sleep techniques of JavaScript one by one.

The shorthand tricks of any programming language are designed to help you write cleaner, more complete code, so that you can implement your requirements with less code. Let’s take a look at some shorthand tricks in JavaScript one by one.

1. Declare multiple variables

//
let x; 
let y = 20; 

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

2. Assign values to multiple variables

We can assign values to multiple variables in one line with array destructuring.

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;
 
/ / short
let [a, b, c] = [5.8.12];
Copy the code

3. Use ternary operators appropriately

We can save 5 lines of code here with ternary (conditional) operator.

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'; 
} 
/ / short
let result = marks >= 30 ? 'Pass' : 'Fail';
Copy the code

4. Specify the default value

We can use OR(||) short circuit evaluation to assign a default value to a variable in case the expected value found falsy.

We can use the “OR (| |) short circuit is evaluated” logic, given a default value. When | | our expectations is a “falsy 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 are calling a function only if a variable is true, then you can use AND(&&) short circuit as an alternative for this.

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

//
if (isLoggedin) {
 goToHomepage(); 
} 

/ / short
isLoggedin && goToHomepage();
Copy the code

The AND(&&) short circuit shorthand is more useful in React when you want to conditionally render a component. For example:

In React, you can use the AND(&&) abbreviation when you want to conditionally render a component. Take the following example 👇

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

Note: Use caution when using special Falsy values such as 0

6. Swap the values of two variables

To swap two variables, we often use a third variable. We can swap two variables easily with array destructuring assignment.

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; 

// Short for using arrays to deconstruct assignments
[x, y] = [y, x];
Copy the code

7. Use arrow functions

//
function add(num1, num2) { 
   return num1 + num2; 
} 

/ / short
const add = (num1, num2) = > num1 + num2;
Copy the code

See “Arrow function”

8. Template string

We normally use + operator to concatenate string values with variables. With ES6 template literals we can do it in a more simple way.

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); 

/ / short
console.log(`You got a missed call from ${number} at ${time}`);
Copy the code

9. Multi-line strings

For multiline string we normally use + operator with a new line escape sequence (\n). We can do it in an easier way by using backticks (`)

For multi-line strings, we usually implement a concatenation of the + operator with a new line break (\n). This can be done more easily 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.' ); 

/ / short
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 multiple value matching, we can put all values in array and use indexOf() or includes() method.

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

//
if (value === 1 || value === 'one' || value === 2 || value === 'two') { 
     // Execute some code
} 

/ / short 1
if ([1.'one'.2.'two'].indexOf(value) >= 0) { 
    // Execute some code
}
/ / short 2
if ([1.'one'.2.'two'].includes(value)) { 
    // Execute some code
}
Copy the code

11. Object attribute allocation

If the variable name and object key name is same then we can just mention variable name in object literals instead of both key and value. JavaScript will automatically set the key same as variable name and assign the value as variable value.

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}; 

/ / short
let obj = {firstname, lastname};
Copy the code

12. Converting a String to a Number

There are built in methods like parseInt and parseFloat available to convert a string to number. We can also do this by simply providing a unary operator (+) in front of string value.

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 average = parseFloat('42.6'); 

/ / short
let total = +'453'; 
let average = +'42.6';
Copy the code

13. Repeat a string multiple times

To repeat a string for a specified number of time you can use a for loop. But using the repeat() method we can do it in a single line.

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 

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

Want to apologize to someone by sending 100 times “Sorry”? Try it with repeat() method. If you want to repeat each string in a new line, then add \n to the string.

Want to say sorry to someone 100 times? Try the repeat() method instead. If you want each string to be on one line, add a newline character (\n) to the end of the string.

// I want to say 100 sorry to you!
'sorry\n'.repeat(100);
Copy the code

14. Power!

We can use Math.pow() method to find the power of a number. There is a shorter syntax to do it with double asterik (**).

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); / / 64

/ / short
const power = 4支那3; / / 64
Copy the code

15. Double NOT operator (~~)?

The double NOT bitwise operator is a substitute for Math.floor() method.

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

//
const floor = Math.floor(6.8); / / 6

/ / short
const floor = ~~6.8; / / 6
Copy the code

Improvement from comment by Caleb: The double NOT bitwise operator approach only works for 32 bit integers i.e (231)-1 = 2147483647. So for any number higher than 2147483647, bitwise operator (~~) will give wrong results, so recommended to use Math.floor() in such case.

Thanks to Caleb for reminding me: the double-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 for loop to loop through each value of array and find the max or min value. We can also use the Array.reduce() method to find the max and min number in 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 spread operator we can do it in a single line.

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

/ / short
const arr = [2.8.15.4]; 
Math.max(... arr);// Maximum 15
Math.min(... arr);// Minimum value 2
Copy the code

17. For loops

To loop through an array we normally use the traditional for loop. We can make use of the for… of loop to iterate through arrays. To access the index of each value we can use for… in loop.

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 loop
for (let i = 0; i < arr.length; i++) { 
  console.log(arr[i]); 
} 

/ / short

// for... Of circulation
for (const val of arr) { 
  console.log(val); 
} 

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

We can also loop through object properties using for… in loop.

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

Reference: Several different ways to iterate over objects and arrays in JavaScript

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 deep clone a multi-level object, we can iterate through each property and check if the current property contains an object. If yes, then do a recursive call to the same function by passing the current property value (i.e. the nested object).

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.

We can also do it by using JSON.stringify() and JSON.parse() if our object doesn’t contains functions, undefined, NaN or Date as values.

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

If we have single level object i.e no nested object present, then we can deep clone using spread operator also.

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}}; 

// We can write it recursively
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); 

// Short for special cases (where an attribute value in an object has no function, undefined, or NaN)
const cloneObj = JSON.parse(JSON.stringify(obj));

// Short for single-layer objects (no nested objects)
let obj = {x: 20.y: 'hello'};
constcloneObj = {... obj};Copy the code

Improvement from comment: The Dictate technique (Json.parse (json.stringify (obj))) doesn’t work if your object property contains function, undefined or NaN as value. Because when you JSON.stringify the object, the property containing function, undefined or NaN as value gets removed from the object. So use JSON.parse(JSON.stringify(obj)) when your object contains only strings and numbers.

Thanks for the reminder in the comments section: The ** json.parse (json.stringify (obj)) ** shorthand will not work if your object attributes include function, undefined, or NaN as the attribute value. Because when you perform json.stringify on an object, properties that contain functions, undefined, or NaN as values are removed from the object. Use json.parse (json.stringify (obj)) only if your object contains only strings and numbers.

Reference: json.parse () and json.stringify ()

20. Get a character in a string

let str = 'jscurious.com'; 

//
str.charAt(2); // c 

/ / short
str[2]; // c
Copy the code

Some of these individuals may not seem relevant to use in project but it’s not bad to know Some extra techniques. Some of these shorthand tips may not seem appropriate for a project, but knowing is better than not knowing.

Happy coding!

Code it! Code it! Code it! 支那

Summary of proper Nouns:

Chinese English
Shorthand skills shorthand techniques
The assignment assign value
Array destruct assignment array destructuring assignment
Conditional operator conditional operator
Expansion operator spread operater
Deep copy deep clone
expectations expected value
Multiple values match multiple value matching
Built-in methods built in method
Recursive calls recursive call
Nested objects nested object
Template strings (template literals) template literals