in

How to Use the Spread Operator in JavaScript—SitePoint

1664954656javascript spread operator

[ad_1]

In this tutorial, we’ll explore different ways to use spread operators in JavaScript and the key differences between spread and rest operators.

three dots (...), the JavaScript spread operator was introduced in ES6. Can be used to expand the elements of collections and arrays into single individual elements.

You can use the spread operator to create and duplicate arrays and objects, pass arrays as function parameters, and remove duplicates from arrays.

syntax

The spread operator can only be used with iterable objects. Must be used immediately before an iterable object, without isolation. for example:

console.log(...arr);

function parameter

Take the Math.min() method as an example. This method accepts at least one number as a parameter and returns the smallest number among the passed parameters.

If you have an array of numbers and you want to find the minimum value of these numbers, you can pass the elements one by one using the index or use the apply() method to pass the elements one by one without using the spread operator. must pass. Array as a parameter. for example:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min.apply(null, numbers);
console.log(minNumber); 

the first parameter is nullbecause the first parameter is used to change the value of this of the calling function.

The spread operator is a more convenient and readable solution for passing array elements as parameters to functions. for example:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min(...numbers);
console.log(numbers); 

You can see it in this live example:

look at the pen
Using spread operator in function JS by SitePoint (@SitePoint)
with a code pen.

create an array

You can use the spread operator to create new arrays from existing arrays or other iterable objects with the Symbol.iterator() method. these are, for...of loop.

For example, it can be used to clone an array. If you just assign the values ​​of the existing array to the new array, any changes to the new array will update the existing array.

const numbers = [15, 13, 100, 20];
const clonedNumbers = numbers;
clonedNumbers.push(24);
console.log(clonedNumbers); 
console.log(numbers); 

The spread operator allows an existing array to be duplicated into a new array, and changes made to the new array do not affect the existing array.

const numbers = [15, 13, 100, 20];
const clonedNumbers = [...numbers];
clonedNumbers.push(24);
console.log(clonedNumbers); 
console.log(numbers); 

Note that this only replicates 1D arrays. It doesn’t work with multidimensional arrays.

You can also use the spread operator to concatenate multiple arrays into one. for example:

const evenNumbers = [2, 4, 6, 8];
const oddNumbers = [1, 3, 5, 7];
const allNumbers = [...evenNumbers, ...oddNumbers];
console.log(...allNumbers); 

You can also use the spread operator on strings to create an array where each item is a character in the string.

const str = 'Hello, World!';
const strArr = [...str];
console.log(strArr); 

create an object

The spread operator can be used to create objects in various ways.

Can be used for shallow duplication of another object. for example:

const obj = { name: 'Mark', age: 20};
const clonedObj = { ...obj };
console.log(clonedObj); 

It can also be used to combine multiple objects into one. for example:

const obj1 = { name: 'Mark', age: 20};
const obj2 = { occupation: 'Student' };
const clonedObj = { ...obj1, ...obj2 };
console.log(clonedObj); 

Note that if objects share the same property name, the value from the last object spread will be used. for example:

const obj1 = { name: 'Mark', age: 20};
const obj2 = { age: 30 };
const clonedObj = { ...obj1, ...obj2 };
console.log(clonedObj); 

You can create an object from an array using the spread operator. The index in the array becomes the property, and the value at that index becomes the value of the property. for example:

const numbers = [15, 13, 100, 20];
const obj = { ...numbers };
console.log(obj); 

It can also be used to create objects from strings. Similarly, the index in the string becomes the property, and the character at that index becomes the value of the property. for example:

const str = 'Hello, World!';
const obj = { ...str };
console.log(obj); 

Convert NodeList to Array

A NodeList is a collection of nodes, which are elements in the document. Elements are accessed through methods in the collection such as: item again entrieswhich is different from an array.

You can convert a NodeList to an array using the spread operator. for example:

const nodeList = document.querySelectorAll('div');
console.log(nodeList.item(0)); 
const nodeArray = [...nodeList];
console.log(nodeList[0]); 

remove duplicates from array

A Set object is a collection that stores only unique values. As with NodeList , we can use the spread operator to convert Set to an array.

Since Set stores only unique values, it can be combined with the spread operator to remove duplicates from an array. for example:

const duplicatesArr = [1, 2, 3, 2, 1, 3];
const uniqueArr = [...new Set(duplicatesArr)];
console.log(duplicatesArr); 
console.log(uniqueArr); 

Spread and rest operators

The rest of the operators are also the 3-dot operator (...), but it serves a different purpose. You can use the rest operator in a function’s parameter list to indicate that this function accepts an undefined number of parameters. These parameters can be treated as arrays.

for example:

function calculateSum(...funcArgs) {
  let sum = 0;
  for (const arg of funcArgs) {
    sum += arg;
  }

  return sum;
}

In this example, the rest operator is calculateSum function. Then loop through the items in the array and sum them to calculate the sum.

Then one by one the variables calculateSum Use a function as an argument, or pass an array element as an argument using the spread operator.

console.log(calculateSum(1, 2, 3)); 
const numbers = [1, 2, 3];
console.log(calculateSum(...numbers)); 

Conclusion

Diffusion operators let you do more with fewer lines of code while maintaining code readability. It can be used with iterables to pass parameters to functions or create arrays and objects from other iterables.

Related reading:

[ad_2]

Source link

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *

GIPHY App Key not set. Please check settings

    442f twittercard npm2 sandbox

    JavaScript sandbox vm2 remediates remote code execution risk

    best small business website builders

    Best small business website builders in 2022