21. MEDIUM | Spread Operator in JavaScript
This article will talk about spread operator in javascript.
The spread operator (...) in JavaScript is used to expand or unpack elements of an iterable into individual elements.
Introduced in ES6.
const arr = [1,2,3];
console.log(...arr); // Output: 1, 2, 3
const str = 'shubham';
console.log(...str); // Output: s, h, u, b, h, a, m
const obj = {name: 'shubham', age: 25};
console.log(...obj);
// Uncaught TypeError: Spread syntax requires ...iterable[Symbol.iterator] to be a function
Use Cases
1. Copying Arrays/Objects (Shallow Copy): The spread operator creates a new instance, preventing unintended mutation of the original data when making changes to the copy.
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray]; // A new array is created
const originalObj = {
name: 'shubham',
age: 25,
address: {city: 'Noida', state: 'UP'}
};
const copiedObj = {...originalObj}; // A new object is created
2. Merging Arrays/Objects: You can combine multiple arrays or objects into a single new one.
- Arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4]
- Objects: If properties have the same name, the value from the last object in the spread sequence will overwrite previous ones.
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObject = { ...obj1, ...obj2 }; // Output: { a: 1, b: 3, c: 4 }
3. Passing Elements as Function Arguments: The spread operator can expand an array into individual arguments for a function call.
function sum(a, b, c) {
console.log(a + b + c);
}
const numbers = [1, 2, 3];
sum(...numbers); // Output: 6
const name = 'Shubham';
sum(...name); // Output: Shu
4. Converting Iterables to Arrays: The spread operator can convert other iterable objects (like strings, Sets, or NodeLists) into an array.
const str = 'Hello';
const strArr = [...str]; // ['H', 'e', 'l', 'l', 'o']
5. Adding Elements While Copying
const numbers = [2, 3, 4];
const newNumbers = [1, ...numbers, 5];
console.log(newNumbers); // Output: [1, 2, 3, 4, 5]
const user = { name: "Shubham", age: 25 };
const newUser = { ...user, city: "Delhi" };
console.log(newUser); // Output: { name: "Shubham", age: 25, city: "Delhi" }
Happy reading!

