It is very confusing to use spread and rest operator in javaScript because both have same syntax (...) but working is totally different .
Let's see the difference between them.
Spread Operator : The spread operator is used to expand or spread individual values of an array or properties of an object.
Code Example :
const arr = [1, 2];
console.log(...arr); // 1 2
It takes [1, 2] and spread values of array and return 1 2.
Function Example :
with spread operator
function add (a , b){
return a+b;
}
const arr = [3 , 4];
console.log(add(...arr)); // 3 ,4 we spread the values of array.
Same function without spread operator
function add(a, b)
{
return a + b;
}
const arr = [3, 4];
console.log(add(arr[0], arr[1])); // 7
Rest Operator : It is opposite of spread operator. It collect all remaining properties from an object or array in a new array or object.
with rest operator
function sum(...nums)
{
console.log(nums);
}
sum(1, 2, 3); // [1, 2, 3]
without rest operator
function sum()
{
const nums = Array.from(arguments);
console.log(nums);
}
sum(1, 2, 3); // [1, 2, 3]
Now you understand the basic working of spread and rest operator. Let's the use cases of both operators.
Use Cases of Spread Operator :
Copy an array :
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
console.log(arr2); // [1, 2, 3]
Merge arrays :
const a = [1, 2];
const b = [3, 4];
const result = [...a, ...b];
console.log(result); // [1, 2, 3, 4]
Add Element in array :
const arr = [1, 2];
const newArr = [...arr, 3, 4];
console.log(newArr); // [1, 2, 3, 4]
Copy Object :
const user = { name: "Abhi", age: 20 };
const newUser = { ...user };
console.log(newUser);
Merge Objects :
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const result = { ...obj1, ...obj2 };
console.log(result); // { a: 1, b: 2 }
Override Values :
const user = { name: "Abhi", age: 20 }; // age = 20
const updated = { ...user, age: 25 };
console.log(updated); // age updated now age = 25
Shallow Copy : A shallow copy creates a new array or object by copying only the first level of data. Nested objects and arrays are not copied; they remain shared by reference with the original.
Conclusion :
In this blog, we explored the core concepts of destructuring, rest, and spread operators in JavaScript. We understood how destructuring helps extract values in a clean and readable way, while the spread operator expands data and the rest operator collects it efficiently.
We also learned important concepts like shallow copy and how nested objects and arrays are still shared by reference.
Top comments (0)