JavaScript Spread and Rest Operators: Real Use Cases

🚀 Where to Use Spread (...) and Rest (...) Operators in JavaScript (Real Use Cases) Many developers know spread and rest… But the real question is 👉 Where should you actually use them? 🔹 Spread Operator (...) → “Expand Values” 👉 Use spread when you want to open / copy / merge data 1. Copy Arrays (Avoid Bugs) const arr = [1, 2, 3]; const copy = [...arr]; 👉 Without spread: const copy = arr; // ❌ same reference (danger) 2. Merge Arrays const a = [1, 2]; const b = [3, 4]; const result = [...a, ...b]; 👉 Very common in real apps 3. Update Objects (Immutability – VERY IMPORTANT in React) const user = { name: "Javascript" }; const updatedUser = { ...user, age: 21 }; 👉 Don’t mutate original object 4. Pass Array as Function Arguments const nums = [5, 10, 2]; Math.max(...nums); 5. Clone Objects const newUser = { ...user }; 👉 Used in state updates (React) 🔹 Rest Operator (...) → “Collect Values” 1. Functions with Unlimited Arguments function sum(...numbers) { return numbers.reduce((a, b) => a + b); } 👉 Flexible functions 2. Separate Values from Array const [first, ...rest] = [1, 2, 3, 4]; 👉 Extract first → collect remaining 3. Remove Properties from Object const user = { name: "Javascript", age: 21, city: "Hyd" }; const { name, ...others } = user; 👉 Useful for filtering data 4. Handling API Data const { id, ...userData } = response; 👉 Separate important fields >>>Spread = “Break it apart” >>> Rest = “Bring it together” “Both use ... , how do you differentiate?” It depends on context — >> If it’s expanding values → Spread >> If it’s collecting values → Rest Example: function demo(a, b, ...rest) {  console.log(a, b, rest); } const arr = [1, 2, 3, 4]; demo(...arr); #JavaScript #WebDevelopment #Frontend #ReactJS #Coding #Developers #LearnJavaScript #100DaysOfCode

To view or add a comment, sign in

Explore content categories