📜 ⬆️ ⬇️

Javascript: 7 useful things

The author of the note, the translation of which we are publishing today, says that in JavaScript, like in any other programming language, you can find a lot of small tricks designed to solve a variety of tasks, both simple and quite complex. Some of these techniques are widely known, and others, not so common, may pleasantly surprise those who do not know about them. Now we will look at 7 useful JavaScript programming techniques.



1. Getting unique array values


In JavaScript, creating an array containing only unique values from another array is probably simpler than you think:

var j = [...new Set([1, 2, 3, 3])] // [1, 2, 3] 

I like how this task can be solved by sharing the operator ... and the data type Set .
')

2. Arrays and Boolean Values


Have you ever needed to remove values from an array , casting them to a logical type gives false ? For example, these are values ​​such as 0 , undefined , null , false . Perhaps you did not know that in order to do this, you can do this:

 myArray   .map(item => {       // ...   })   //       .filter(Boolean); 

As you can see, in order to get rid of all such values, it is enough to pass the Boolean method to the arrays .filter() .

3. Creating Truly Empty Objects


I am sure that you can create an object that appears to be empty using the syntax of the object literal: {} . But such an object will be assigned a prototype ( __proto__ ), it will have a method hasOwnProperty() and other methods of objects. In order to create a truly empty object , which can, for example, be used as a “dictionary”, you can do this:

 let dict = Object.create(null); // dict.__proto__ === "undefined" //        ,           

In an object created in this way, there are no properties and methods that are not added to it by the programmer.

4. Merge objects


Those who wrote in JavaScript always needed to create such objects that would include the contents of other objects. This task became especially urgent when classes appeared in JavaScript, when programmers had to work with something like widget program representations. Here's how to create a new object based on several other objects:

 const person = { name: 'David Walsh', gender: 'Male' }; const tools = { computer: 'Mac', editor: 'Atom' }; const attributes = { handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue' }; const summary = {...person, ...tools, ...attributes}; /* Object { "computer": "Mac", "editor": "Atom", "eyes": "Blue", "gender": "Male", "hair": "Brown", "handsomeness": "Extreme", "name": "David Walsh", } */ 

Operator ... greatly simplifies the solution of the problem of merging objects.

5. Required function parameters


Setting the default values ​​of function arguments was an excellent extension of JavaScript capabilities. But how to make it so that without transferring some of the required parameters of the function simply refuse to work:

 const isRequired = () => { throw new Error('param is required'); }; const hello = (name = isRequired()) => { console.log(`hello ${name}`) }; //    ,     name hello(); //     hello(undefined); //        hello(null); hello('David'); 

Before us is an additional level of testing what is passed to functions.

6. Destructuring assignment and new names of extracted properties of objects


Destructuring is a new, useful feature of JavaScript, but sometimes properties extracted from objects need to be assigned names that differ from those they have in these objects. Here's how to do it:

 const obj = { x: 1 }; //      obj.x   x const { x } = obj; //   obj.x     otherName const { x: otherName } = obj; 

This technique is useful in cases where you need to avoid the conflict of names of variables or constants.

7. Parsing query strings


For many years, we wrote regular expressions to parse query strings, but these times are over. Now, to solve this problem, you can use the wonderful API URLSearchParams :

 // ,     "?post=1234&action=edit" var urlParams = new URLSearchParams(window.location.search); console.log(urlParams.has('post')); // true console.log(urlParams.get('action')); // "edit" console.log(urlParams.getAll('action')); // ["edit"] console.log(urlParams.toString()); // "?post=1234&action=edit" console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1" 

Using the URLSearchParams API URLSearchParams much easier than solving the same problems using regular expressions.

Results


Modern JavaScript is developing very fast, various useful improvements are constantly appearing in it. But the improvement of the language does not mean that programmers do not need to think about the code and look for effective solutions to various problems facing them. We hope those little tricks of JavaScript that we talked about today will be useful to you.

Dear readers! Do you know any useful JS programming techniques? If so, ask them to share.

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


All Articles