13 useful JavaScript single-liners

Original author: Tuan Pham-Barnes
  • Transfer
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 single-line files - code fragments, surprisingly powerful, given that they fit on one line. According to him, great opportunities are also a big responsibility, so you need to use these designs carefully, trying to ensure that they do not harm the readability of programs. Here are 13 single-line players. Examples prepared using Node.js v11.x. If you use them in another environment, this may affect their execution.





1. Coercion of values ​​to logical type


Here's how to cast a value to a boolean type:

const myBoolean = !!myVariable;

Double negation ( !!) is necessary so that a value that is true from the point of view of JavaScript rules is converted to true, and false to false.

2. Getting rid of duplicate values ​​in arrays


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

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

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

3. Creating and setting properties of objects by condition


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

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

If, as a result of calculating the left side of the expression, something is received that JS perceives as a false value, then &&no further calculations will be performed and a new property will not be created and set. The object myObjectwill be empty. If the construction ...myPropertyreturns some result that JS perceives as true, due to the construction &&, a property will appear in the object propNamethat stores the received value.

4. Merging 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 names, only one such property will remain in the final object, which belongs to the one from the original objects, which is located to the right of the others. Please note that small copying of object properties is used here.

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 varAwill fall into varB, and vice versa. This is possible thanks to the use of internal mechanisms of destructuring.

6. Removing false values ​​from the array


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

const clean = dirty.filter(Boolean);

During this operation it is removed from the array values such as null, undefined, false, 0, and as blank lines.

7. Converting numbers to strings


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

const stringArray = numberArray.map(String);

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

You can also perform the inverse transformation - converting the type Stringvalues ​​to the type values Number:

const numberArray = stringArray.map(Number);

8. Retrieving object property values


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

const { original: newName } = myObject;

Through the use of this construction, a new constant will be created newName, in which the value of the property of the originalobject will be written myObject.

9. Formatting JSON code


Here's how to convert the JSON code to a readable look:

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

The method stringifytakes three parameters. The first is a JavaScript object. The second, optional, is a function that can be used to process JSON code resulting from the conversion of the 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 received JSON code will be one long string. If the object myObjhas circular references, 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 the six-digit code used in two-factor authentication mechanisms or in other similar ones, you can do this:

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

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

12. Array mixing


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

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

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

13. Creating deep copies of objects


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

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

It should be noted that if originalObjectthere are circular links, then you will not be able to create a copy of it. This technique is recommended for use on simple objects that you create yourself.

A shallow copy of the object can be created using the spread syntax:

const myClone = { ...orignalObject };

Summary: on combining and expanding single-line code


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

Dear readers! What examples of useful JS single-lineers would you add to this material?




Also popular now: