πŸ“œ ⬆️ ⬇️

9 useful tricks for those who program in JavaScript

The author of the material, the translation of which we are publishing today, talks about nine useful work techniques that can be useful to a JavaScript programmer. He says that these techniques save time and that they are used by professionals.



1. Cleaning or truncating an array


In order to clear an array or reduce its length, you can change its length property. In this case, for example, there is no need to, in order to clear an array, write to a variable that stores a reference to it, a reference to a new array.

 const arr = [11, 22, 33, 44, 55, 66]; //   arr.length = 3; console.log(arr); //=> [11, 22, 33] //   arr.length = 0; console.log(arr); //=> [] console.log(arr[2]); //=> undefined 

2. Imitation of named parameters during object destructuring


It is very likely that you already use objects with parameters in cases where you need to pass a variable set of parameters to a function. For example, it might look like this:
')
 doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 }); function doSomething(config) { const foo = config.foo !== undefined ? config.foo : 'Hi'; const bar = config.bar !== undefined ? config.bar : 'Yo!'; const baz = config.baz !== undefined ? config.baz : 13; // ... } 

This is an old but effective pattern that is used to simulate named parameters in JavaScript. Calling such a function looks quite normal, but, on the other hand, too much code is needed to implement the logic of processing an object with parameters. Due to the possibilities for destructuring ES2015 objects, this disadvantage can be circumvented:

 function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) { // ... } 

And, if you need to make an object with parameters optional, this also does not cause difficulties:

 function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) { // ... } 

3. Restructuring and array elements


Here's how to assign the elements of an array to individual variables using the restructuring features:

 const csvFileLine = '1997,John Doe,US,john@doe.com,New York'; const { 2: country, 4: state } = csvFileLine.split(','); 

4. Using ranges of values ​​in the switch statement


Here is a simple technique that demonstrates the use of value ranges in a switch :

 function getWaterState(tempInCelsius) { let state; switch (true) {   case (tempInCelsius <= 0):     state = 'Solid';     break;   case (tempInCelsius > 0 && tempInCelsius < 100):     state = 'Liquid';     break;   default:     state = 'Gas'; } return state; } 

5. Organization of waiting for several asynchronous functions in the async / await construction


Thanks to the following technique, in which Promise.all used, it is possible to organize waiting for the execution of several asynchronous functions:

 await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()]) 

6. Creating clean objects


If necessary, you can create an absolutely empty, clean object that does not inherit any properties and methods from Object (for example, it is a constructor , toString() and so on). Here's how to do it:

 const pureObject = Object.create(null); console.log(pureObject); //=> {} console.log(pureObject.constructor); //=> undefined console.log(pureObject.toString); //=> undefined console.log(pureObject.hasOwnProperty); //=> undefined 

7. Formatting JSON Code


The JSON.stringify method is capable of more than the usual conversion of objects into their string representation. In particular, the resulting JSON code with this method can be formatted:

 const obj = { foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } } }; //   -   ,    //  JSON-. JSON.stringify(obj, null, 4); // =>"{ // =>    "foo": { // =>        "bar": [ // =>            11, // =>            22, // =>            33, // =>            44 // =>        ], // =>        "baz": { // =>            "bing": true, // =>            "boom": "Hello" // =>        } // =>    } // =>}" 

8. Removing duplicate array elements


Using an object of type Set from ES2015 with an extension operator makes it easy and convenient to remove duplicate elements from arrays:

 const removeDuplicateItems = arr => [...new Set(arr)]; removeDuplicateItems([42, 'foo', 42, 'foo', true, true]); //=> [42, "foo", true] 

9. Linearization of multidimensional arrays


Linearization of arrays using the extension operator is an extremely simple task:

 const arr = [11, [22, 33], [44, 55], 66]; const flatArr = [].concat(...arr); //=> [11, 22, 33, 44, 55, 66] 

Unfortunately, the above technique works only for two-dimensional arrays. However, due to recursion, we can use this method for arrays with more than two dimensions:

 function flattenArray(arr) { const flattened = [].concat(...arr); return flattened.some(item => Array.isArray(item)) ?   flattenArray(flattened) : flattened; } const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]]; const flatArr = flattenArray(arr); //=> [11, 22, 33, 44, 55, 66, 77, 88, 99] 

Results


We hope those tricks that you learned about from this material will help you improve your JavaScript programs and save some time.

Dear readers! Do you know any unobvious things that JS developers might need? If so, please talk about them.

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


All Articles