JavaScript Spread Operators – Explained with Code Examples
In javascript Spread operator is represented by three dots ... and is used to expand or spread out elements of an iterable such as an array, string, object.
Here are few common use cases:
- Copying an array
const originalArray = [10,20,30];
const copiedArray = [...originalArray];
console.log(copiedArray); // [10,20,30]
Concatenation of arrays
const num1 = [1,2,3]; const num2 = [4,5,6]; const concatNum = [...num1,num2]; console.log(concatnum); // [1,2,3,4,5,6] // we can add few more elements even const moreNum = [...num1,...num2, 7,8,9,10];
Spread Operator in Objects:
Merging Objects:
const obj1 = {
name:'subham',
age: 25
}
const obj2 = {
city: 'New Delhi',
job: 'Developer',
}
const mergedObj = {...obj1,...obj2}
console.log(mergedObj) //{name:'subham',age:25,city:'New Delhi',job:'Developer'}
Spread Operator as part of Function Parameter
function sum(x,y,z){
return x+y+z;
}
const num = [1,2,3];
console.log(sum(...num)); //6
Here's a real-world example of using the spread operator in JavaScript, demonstrating how to merge two objects representing a user's profile and settings.
Scenario
Imagine you have two objects: one containing a user's profile information and another containing their settings. You want to combine these two objects into a single object that represents the complete user data.
// User profile object
const userProfile = {
id: 1,
name: "John Doe",
email: "john.doe@example.com"
};
// User settings object
const userSettings = {
theme: "dark",
notifications: true,
language: "en"
};
// Merging the two objects using the spread operator
const completeUserData = {
...userProfile,
...userSettings
};
console.log(completeUserData);
Summary
The spread operator (...
) in JavaScript is a powerful feature that allows you to easily expand, copy, or merge objects and arrays. By using the spread operator, you can create new objects or arrays that include all the properties or elements of existing ones, along with any additional properties or elements you specify. This is particularly useful for maintaining immutability, a key concept in modern JavaScript development, especially in frameworks like React. For example, you can merge an object's properties with new data without altering the original object, or combine multiple arrays into one. The spread operator simplifies code, making it more readable and maintainable.
Subscribe to my newsletter
Read articles from Subham Gope directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by