What is the spread operator in JavaScript with example?

  • javascript
  • 96 Views
  • 5 Min Read
  • 9 Jul 2024

JavaScript's spread operator is a feature in the programming language that streamlines data structure manipulation. It is an ES6 feature, represented by three dots (...). It is used to manipulate arrays, strings, and objects. Using this, we can quickly add array elements and merge objects without writing a lot of code.


In this article, we will teach you everything about the spread operator, from the basics to more advanced concepts, so you will become a master of the spread operator. We will also learn how to improve our JavaScript coding skills using the spread operator.

 

Let's discover what the spread operator can do in JavaScript.

 
What is spread operator in JavaScript with example?
 

Syntax: 

 
const newArray = [...oldArray];
 

The spread operator offers simplicity and flexibility in JavaScript programming. There are three key scenarios where spread syntax can be applied:

 

  • Creating a new array or object with all elements or properties included.
  • Passing individual elements as arguments to a function.
  • Combining arrays or objects by spreading their elements or properties.

 

Here are 10 powerful examples demonstrating the versatility and usefulness of the spread operator in JavaScript:

 

  1. Copying Array and Object
  2. Merging Arrays and Objects
  3. Passing Arguments to Functions
  4. Creating Copies with Modifications
  5. Converting NodeList to Array
  6. Using the Spared Operator with Math Functions
  7. Creating New Arrays with Removed Elements
  8. Cloning Objects with Overrides
  9. Concatenating Arrays
  10. Using the Spread Operator With Strings

 

 

1. Copying Array and Object

 
const originalArray = [1, 2,"John"];
const newArray = [...originalArray]; // Copying array
console.log(newArray); // Output: [1, 2, 'John']

const originalObject = { name: 'Elena', age: 21 };
const newObject = { ...originalObject }; // Copying object
console.log(newObject); // Output: { name: 'Elena', age: 21 }
 

When we use [...originalArray], all the elements from the originalArray are spread into a new array called newArray, effectively making a copy of the original array.

 

Similarly, { ...originalObject } spreads the properties of the originalObject into a new object called newObject, essentially creating a clone of the original object.

 

 

2. Merging Arrays and Objects

 
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2]; // Merging arrays
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]

const obj1 = { name: 'Elena' };
const obj2 = { age: 21 };
const mergedObject = { ...obj1, ...obj2 }; // Merging objects
console.log(mergedObject); // Output: { name: 'Elena', age: 21 }
 

The code const mergedArray = [...array1,...array2] combines the elements of array1 and array2 into a new array named mergedArray.

 

Similarly, const mergedObject = {...obj1,...obj2 } creates a new object named mergedObject by combining the properties of obj1 and obj2.

 

The resulting mergedArray and mergedObject are then logged to show the merged arrays and objects.

 

 

3. Passing Arguments to Functions

 
const numbers = [1, 2, 3, 4];
const sum = (a, b, c, d) => a * b * c * d;
console.log(sum(...numbers)); // Output: 24
 

This code example shows how the spread operator (...) passes array elements as arguments to a function. We have a set of numbers, [1, 2, 3, 4]. The function 'sum' multiplies the four parameters (a, b, c, d). Using the spread operator (...) with a list of numbers is the same as passing each number individually to the 'sum' function. So, the function multiplies 1 * 2 * 3 * 4, which gives us 24.

 

 

4. Creating Copies with Modifications

 
  const originalObject = { name: 'John', age: 30 };
  const updatedObject = { ...originalObject, name: "Elena", age: 21 }; // Creating a copy with modification
  console.log(updatedObject); // Output: { name: 'Elena', age: 21 }
  console.log(originalObject); // Output: { name: 'John', age: 30 }
 

This code demonstrates the use of the spread operator (...) to make a modified copy of an object. With the spread operator in 'updatedObject', the properties of 'originalObject' are replicated, replacing the name from 'John' to 'Elena' and the age from 30 to 21. Then, it shows the new object called 'updatedObject'.

 

If we log originalObject after creating updatedObject, it stays the same. This is because the spread operator only creates a shallow copy, keeping the original object unchanged. So, originalObject still has 'name' as 'John' and 'age' as 30.

 

 

5. Converting NodeList to Array

 
const nodeList = document.querySelectorAll('p');
const arrayFromNodeList = [...nodeList];
 

This code uses the spread operator (...) to turn a NodeList, which is a collection of <p> elements selected from the document using the document.querySelectorAll('p'), into an array. By spreading [...nodeList], the elements of the NodeList are copied into a new array called arrayFromNodeList. This transformation allows for easier manipulation and access to the selected <p> elements as an array. 

 
 

6. Using the Spread Operator with Math Functions

 
  const values = [1, 2, 3, 4, 5];
  const max = Math.max(...values); // 5
  const min = Math.min(...values); // 1
  console.log(max, min);
 
In this code snippet, an array named values contains numbers from 1 to 5. The spread operator (...) is then used to pass the elements of the value array as arguments to the Math.max and Math.min functions.
 
This calculates the maximum and minimum values within the array, resulting in max being 5 and min being 1. Finally, both max and min values are logged to the console.
 
 

7. Creating New Arrays with Removed Elements

 
const numbers = [1, 2, 3, 4, 5];
const without3 = [...numbers.slice(0, 2), ...numbers.slice(3)]; 
console.log(without3); // [1, 2, 4, 5]
 
This code begins with an array named 'numbers' containing numbers from 1 to 5. Then, it makes a new array named 'without3' by taking parts of the original array but leaving out the number 3.
 
Using the spread operator (...), it combines these parts together, effectively removing the number 3. Finally, it shows the modified 'without3' array on the console, which now contains [1, 2, 4, 5].
 
 

8. Cloning Objects with Overrides

 
const defaultConfig = { theme: 'light', fontSize: '16px' };
const userConfig = { fontSize: '20px' };
const mergedConfig = { ...defaultConfig, ...userConfig }; // { theme: 'light', fontSize: '20px' }
console.log(mergedConfig);
 
This code merges two objects, defaultConfig, and userConfig, into a new object called mergedConfig. The spread operator { ...defaultConfig, ...userConfig } combines the properties of both objects, favoring the values from userConfig in case of conflicts.
 
Finally, the resulting merged configuration, { theme: 'light', fontSize: '20px' }, is logged to the console.
 
 

9. Concatenating Arrays

 
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const concatenatedArray = [...arr1, ...arr2, 7, 8, 9];
console.log(concatenatedArray);  // [1, 2, 3, 4, 5, 6, 7, 8, 9]
 

This code concatenates two arrays, arr1, and arr2, along with additional elements [7, 8, 9], into a new array called concatenatedArray. The spread operator {...arr1, ...arr2, 7, 8, 9} expands the elements of both arrays and inserts the additional values.

 

Finally, the resulting concatenated array [1, 2, 3, 4, 5, 6, 7, 8, 9] is logged to the console.

 
 

10. Using the Spread Operator with Strings

 
const str = "Elena";
const spreadStr = [...str];
console.log(spreadStr);
 

This code snippet initializes the string variable 'str' with the word "Elena". The spread operator (...) divides the string str into individual characters, providing an array called 'spreadStr' containing ['E', 'l', 'e', 'n', 'a']. Finally, the spreadStr array is displayed on the console.

 
 

Usage of Spread Operators

 

Avoid the use of spread operators with large arrays or objects, especially if performance is important.


To avoid unwanted effects, be careful while spreading nested objects; use deep cloning methods as required.


Use the spread operator carefully, considering its impact on performance; consider different strategies if efficiency becomes a priority.

 

So you can consider alternative options like looping, functional programming (like map, filter, and reduce), custom functions, batch processing, data structure optimization, and library usage. These approaches optimize performance by reducing unnecessary activities and leveraging built-in efficiencies.

 

 

Conclusion

 

As we learned, using the spread operator in JavaScript helps make your code simpler and more effective. It is really useful for tasks like copying arrays and objects, combining data, passing arguments smoothly, and making changes with ease. Whether you're converting NodeLists to arrays, using math functions, or working with strings, the spread operator can handle it all.

 

If you have any questions regarding this article, you can ask them in the question box given below. Share it with your developer's friends so that they can also learn something new. Thank you 

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!

About Author

Username

Meet Soni ( meetsoni )

Software Engineer

Joined On 13 Feb 2024

More from Meet Soni

Top 10 React Carousel Component Libraries for 2024

react-js

9 Jul 2024

Discover the top 10 React carousel libraries for 2024. Choose the best carousel based on i....

What is the spread operator in JavaScript with example?

javascript

9 Jul 2024

Learn how we can easily manipulate arrays, strings, and objects with the help of the sprea....

Top 4 Ways Centering a Div or Text Inside a Div using CSS

css

4 May 2024

Learn 4 techniques to make it easier to center a div container both horizontally and verti....

20 Amazing CSS Properties You Need to know - Part 2

css

4 May 2024

Learn about such properties of CSS with which you can easily make your website more attrac....

20 Amazing CSS Properties You Need to know - Part 1

css

9 May 2024

Learn 10 CSS properties that many developers do not know about. By understanding these all....

30 Keyboard Shortcuts You Might Not Know for Windows

programming

4 May 2024

Learn 30 Windows shortcut keys that will make it easier to use the system. In this post, w....

Popular Posts from Code Mafias

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

Mastering HTML: Top 12 Unique HTML Tags with Examples

html

4 May 2024

Through this article, learn those essential HTML tags that many developers do not know abo....

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....