The spread operator (...
) in JavaScript is a versatile and powerful feature that allows you to expand or spread elements in arrays, objects, or function arguments. It’s commonly used for copying, merging, and passing around data structures without modifying the original ones.
the use of spread operator in Array
Copying an Array:
const arr1 = ["Apple","Banana", "Orange"];
const arr2 = [...arr1];
console.log(arr2); // Output: [Apple,Banana,"Orange]
Combining Arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // Output: [1, 2, 3, 4, 5, 6]
Adding Elements to an Array:
const arr1 = [1, 2, 3];
const arr2 = [0, ...arr1, 4];
console.log(arr2); // Output: [0, 1, 2, 3, 4]
the use of the spread operator in Object
Copying an Object
const obj1 = { name: 'John', age: 38 };
const obj2 = { ...obj1 };
console.log(obj2); // Output: {name: 'John', age: 38}
Merging Objects
const obj1 = { name: 'John', age: 38 };
const obj2 = { sex: 'Male', qualification: 'Graduate'};
const merged = { ...obj1, ...obj2 };
console.log(merged); // Output: {name: 'John', age: 38, sex: 'Male', qualification: 'Graduate' }
Overriding Properties
const obj1 = { name: 'John', age: 38 };
const obj2 = { age: 39, qualification: 'Graduate'};
const merged = { ...obj1, ...obj2 };
console.log(merged); // Output: {name: 'John', age: 39, qualification: 'Graduate' }
Function Arguments
Spreading an Array as Arguments
function sum(a, b, c, d) {
return a+b+c+d;
}
const numbers = [1, 2, 3,4];
console.log(sum(...numbers)); // Output: 10