📜 ⬆️ ⬇️

Javascript es6: extension operator

JavaScript is constantly evolving, there are various innovations and improvements. One of these new features introduced in ES6 is the extension operator. It looks like a three-dot ( ... ). This operator allows you to split iterable objects where either complete absence or the presence of one or several arguments is expected. Dry definitions are usually difficult to understand without practical examples. Therefore, we consider several options for using the extension operator, which will help to penetrate into its essence.

image

Example # 1: Inserting Arrays into Other Arrays


Take a look at this code. Here the extension operator is not used:

 var mid = [3, 4]; var arr = [1, 2, mid, 5, 6]; console.log(arr); 

Above, we created an array of mid . Then a second array is created, arr , which contains an array of mid . At the end of the program, the arr array is output to the console. What do you think this array will become after adding a mid array? Take a look at what the program displays:
')
 [1, 2, [3, 4], 5, 6] 

You thought that would be so?

By inserting the mid array into the arr array, we end up with one array nested in another. If this is exactly what was needed, then there is nothing to quibble about. However, what if the purpose of writing the above code was to get an array of numbers from 1 to 6? In order to achieve this goal, you can use the extension operator. Recall that this operator allows you to split arrays into separate elements.

Consider the following example. Everything here, except for one place, is exactly the same as in the previous code snippet. The difference is that now in order to insert the contents of the array mid into the array arr , the extension operator is used:

 var mid = [3, 4]; var arr = [1, 2, ...mid, 5, 6]; console.log(arr); 

If this code is executed, then the following will be displayed:

 [1, 2, 3, 4, 5, 6] 

Remember the description of the extension operator given at the very beginning of the material. You just saw him in action. As you can see, when we create an array arr and use the extension operator, applying it to the mid array, instead of inserting another array as an object into one array, this other array is “split into pieces”. The separation of the inserted array in our case means that all the elements of this array, one by one, will be added to the arr array. As a result, instead of a construction from nested arrays, we get one array containing numbers from 1 to 6.

Example 2: Mathematical Calculations


JavaScript has a built-in Math object that allows you to perform mathematical calculations. In this example, we are interested in the Math.max() method. If you are not familiar with this method, we inform you that it returns the largest of the numbers passed to it, and it is acceptable to use it without arguments, or with one or more arguments. Here are some examples:

 Math.max(); // -Infinity Math.max(1, 2, 3); // 3 Math.max(100, 3, 4); // 100 

As you can see, if you want to find the maximum value of several numbers, Math.max() needs several parameters. Unfortunately, if you need to find the maximum element of a numeric array, the array itself cannot be passed to the Math.max() method. Before the expansion operator appeared in JS, the easiest way to find the maximum element in an array using Math.max() was to use the apply() method:

 var arr = [2, 4, 8, 6, 0]; function max(arr) { return Math.max.apply(null, arr); } console.log(max(arr)); 

Above is a working construction, but all this does not look very nice.

And here is how the same thing is done with the help of the extension operator:

 var arr = [2, 4, 8, 6, 0]; var max = Math.max(...arr); console.log(max); 

Instead of creating a function and using the apply() method to return the result of the Math.max() method, you only need two lines of code. The extension operator “pulls out” all its elements from an array and they are input to the Math.max() method.

Example 3: copying arrays


In JS, you cannot copy an array simply by equating a new variable with one that already contains an existing array. Consider an example:

 var arr = ['a', 'b', 'c']; var arr2 = arr; console.log(arr2); 

If you do it, you can see the following:

 ['a', 'b', 'c'] 

At first glance, everything works as it should, it may seem that we copied the values ​​of the array from the variable arr into the variable arr2 . However, in fact, something completely different happened. In JavaScript, in the assignment of objects to variables (and arrays are also objects), they operate on references to them, and not their values. This means that the same reference was stored in arr2 , which was stored in arr . In other words, everything we do after this with arr2 will also affect arr (and vice versa). Take a look at this:

 var arr = ['a', 'b', 'c']; var arr2 = arr; arr2.push('d'); console.log(arr); 

Here we put a new element, the string d , at the end of the arr2 array. However, by outputting arr to the console, you can see that the array referenced by this variable has also changed:

 ['a', 'b', 'c', 'd'] 

It should be noted that nothing terrible happens here. Before us is the standard JS behavior. And in order to really create a copy of the array, you can use the extension operator. Here is an example of using this operator to copy arrays. The code looks almost the same as in the above example. However, the extension operator applied to the source array is used here, and the whole structure is enclosed in square brackets:

 var arr = ['a', 'b', 'c']; var arr2 = [...arr]; console.log(arr2); 

By executing this code, you can see that it outputs what we expect from it:

 ['a', 'b', 'c'] 

In this example, the arr array “unfolds”; we have at its disposal its individual elements that fall into a new array, the link to which is written to arr2 . Now you can do anything with arr2 and it will not affect arr :

 var arr = ['a', 'b', 'c']; var arr2 = [...arr]; arr2.push('d'); console.log(arr); 

Again, the reason why this all works is that the extension operator “pulls out” the values ​​of the elements of the arr array and they fall into the new array arr2 . Thus, we write in arr2 link to a new array containing elements from the arr array, and not a link to the array referenced by the arr variable. This is what distinguishes this example from the previous one.

An additional example: converting a string to an array


Finally - here is one interesting example of using an extension operator to convert strings to arrays. Here it is enough to apply this operator to the desired line, putting the whole structure in a pair of square brackets:

 var str = "hello"; var chars = [...str]; console.log(chars); 

Results


Today we reviewed the features of working with the extension operator. This is one of the new features of JavaScript ES6, a useful little thing that is quite capable of improving the readability of the code and reducing its size slightly.

Dear readers! Do you use the extension operator in javascript?

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


All Articles