The Power of Spread and Rest Operators in Real Projects
1️⃣ What Are Spread and Rest Operators?
Both spread and rest use ...
(three dots), but they work in opposite directions:
-
...spread
expands elements. -
...rest
collects remaining elements.
Think of spread as breaking apart and rest as gathering together.
2️⃣ Spread Operator: Expanding Arrays, Objects, and Arguments
🔸 Copying Arrays
const arr = [1, 2, 3];
const copy = [...arr];
console.log(copy); // [1, 2, 3]
🔸 Merging Arrays
const nums1 = [1, 2];
const nums2 = [3, 4];
const merged = [...nums1, ...nums2];
console.log(merged); // [1, 2, 3, 4]
🔸 Spread in Function Calls
function add(a, b, c) {
return a + b + c;
}
const values = [5, 10, 15];
console.log(add(...values)); // 30
🔸 Spreading Objects
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 99, c: 3 };
const result = { ...obj1, ...obj2 };
console.log(result); // { a: 1, b: 99, c: 3 }
✅ Spread overrides earlier keys with the same name.
3️⃣ Rest Operator: Collecting Remaining Arguments or Properties
🔹 Function Parameter
function total(...nums) {
return nums.reduce((sum, n) => sum + n, 0);
}
console.log(total(1, 2, 3, 4)); // 10
🔹 Destructuring Arrays
const [first, ...others] = [10, 20, 30];
console.log(others); // [20, 30]
🔹 Destructuring Objects
const { a, ...rest } = { a: 1, b: 2, c: 3 };
console.log(rest); // { b: 2, c: 3 }
4️⃣ Real-World Use Cases
✅ React Props Passing
function Button({ label, ...rest }) {
return <button {...rest}>{label}</button>;
}
✅ Cloning and Extending Objects
const user = { name: "Sriram", age: 22 };
const updated = { ...user, age: 23 };
✅ Variadic Functions
function logAll(...args) {
console.log("Arguments:", args);
}
logAll("JS", 101, true); // ["JS", 101, true]
✅ Filtering Object Key's
const { password, ...safeData } = userData;
5️⃣ Best Practices and Common Pitfalls
✅ Prefer spread for immutable updates (especially in Redux or state management)
✅ Rest is great for collecting unknown args
❌ Don’t use spread with deeply nested structures (use deep clone utilities)
❌ Spread creates shallow copies only!
This Content Sponsored by Buymote Shopping app
BuyMote E-Shopping Application is One of the Online Shopping App
Now Available on Play Store & App Store (Buymote E-Shopping)
Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8
Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication