📜 ⬆️ ⬇️

13 helpful JavaScript liners

The author of the article, the translation of which we are publishing today, says that he has been programming in JavaScript for many years. During this time, he collected a collection of excellent one-liners - code fragments, surprisingly powerful, given that they fit into one line. According to him, great opportunities are also a big responsibility, therefore it is necessary to use these structures carefully, trying to ensure that they would not harm the readability of programs.



Here are 13 one-liners. Examples are prepared using Node.js v11.x. If you use them in a different environment, this may affect their implementation.

1. Reduction of values ​​to a logical type


Here's how to bring a certain value to a logical type:
')
const myBoolean = !!myVariable; 

Double negation ( !! ) is necessary in order for a value that is true from the point of view of JavaScript rules to be converted to true and false to false .

2. Disposal of duplicate values ​​in arrays


Here's how to remove duplicate values ​​from an array:

 const deDupe = [...new Set(myArray)]; 

Set data structures store only unique values. As a result, the use of such a data structure and syntax spread allows you to create a new array based on the myArray array, in which there are no duplicate values.

3. Creating and setting object properties by condition


In order to set properties of objects using the && operator, you can use the spread syntax:

 const myObject = { ...myProperty && { propName: myProperty } }; 

If, as a result of the calculation of the left part of the expression, something is received that is perceived by JS as a false value, then && will not perform further calculations and the new property will not be created and set. myObject will be empty. If the construct ...myProperty returns some result perceived by JS as true, thanks to the && construct, the propName property will appear in the object, storing the resulting value.

4. Merge objects


Here's how to create a new object in which two other objects will be combined:

 const mergedObject = { ...objectOne, ...objectTwo }; 

This approach can be used to organize the merger of an unlimited number of objects. Moreover, if the objects have properties with the same name, in the final object there will be only one such property belonging to that of the original objects, which is located to the right of the others. Please note that this uses shallow copying of object properties.

5. Exchange of variable values


In order to exchange values ​​between two variables without using an auxiliary variable, you can do this:

 [varA, varB] = [varB, varA]; 

After that, what was in varA will fall into varB , and vice versa. This is possible due to the use of internal destructuring mechanisms.

6. Removing False Values ​​from an Array


Here's how to remove from the array all values ​​that are considered false in JavaScript:

 const clean = dirty.filter(Boolean); 

During the execution of this operation, such values ​​as null , undefined , false , 0 , as well as empty strings will be deleted from the array.

7. Converting numbers to strings


In order to convert the numbers stored in the array, in their string representation, you can do this:

 const stringArray = numberArray.map(String); 

The string elements of the array during such a transformation will remain string.

You can also do the inverse transformation by converting values ​​of type String to values ​​of type Number :

 const numberArray = stringArray.map(Number); 

8. Retrieving Property Property Values


Here's how to retrieve the value of an object property and write it into a constant whose name is different from the name of this property:

 const { original: newName } = myObject; 

By using this construct, a new constant will be created, newName , in which the value of the original property of myObject will be written.

9. Formatting JSON Code


Here's how to convert JSON code to a view that is convenient for perception:

 const formatted = JSON.stringify(myObj, null, 2); 

The stringify method takes three parameters. The first is a JavaScript object. The second, optional, is a function that can be used to process the JSON code that results from the conversion of an object. The last parameter indicates how many spaces should be used when indenting in JSON code. If you omit the last parameter, then all the resulting JSON code will be a single long string. If there are circular references in the myObj object, it cannot be converted to JSON format.

10. Quickly create numeric arrays


Here's how to create an array and fill it with numbers:

 const numArray = Array.from(new Array(52), (x, i) => i); 

The first element of such an array has an index of 0. The size of the array can be specified using either a numeric literal or a variable. Here we create an array of 52 elements, which, for example, can be used to store data about a deck of cards.

11. Creation of codes for two-factor authentication


In order to generate a six-digit code used in two-factor authentication mechanisms or other similar mechanisms, you can do this:

 const code = Math.floor(Math.random() * 1000000).toString().padStart(6, "0"); 

Note that the number of zeros in the number by which the result returned by Math.random() is multiplied must correspond to the first parameter ( targetLength ) of the padStart method.

12. Mixing an array


In order to mix an array without knowing what exactly it contains, you can do this:

 myArray.sort(() => { return Math.random() - 0.5}); 

There are also better algorithms for mixing arrays. For example, the Fisher-Yates shuffle algorithm. Read about different algorithms for mixing arrays here .

13. Making deep copies of objects


The method of deep copying of objects proposed here does not have a particularly high performance. But if you need to solve this problem with the use of a one-liner - you can use the following code:

 const myClone = JSON.parse(JSON.stringify(originalObject)); 

It should be noted that if there are circular references in the originalObject , then you cannot create a copy of it. This technique is recommended for use on simple objects that you create yourself.

You can create a shallow copy of an object using the spread syntax:

 const myClone = { ...orignalObject }; 

Results: on combining and expanding the code of one-liners


There are many ways to combine code snippets presented here. This allows us to solve many problems with their help and at the same time to use very compact language constructs. The author of this material believes that in the course of the evolution of JavaScript, new features will appear in it that will contribute to writing compact and powerful code.

Dear readers! What examples of useful JS one-line users would you add to this material?



Source: https://habr.com/ru/post/456338/


All Articles