JavaScript Spread & Rest Operators Explained

Spread & Rest Operators in JavaScript. If you're learning JavaScript, these two operators are super important and very useful in real projects. --- Spread Operator ("...") Definition: The spread operator is used to expand elements of an array or object. It “spreads out” values. Common Use Cases: 1. Copying Arrays const arr1 = [1, 2, 3]; const arr2 = [...arr1]; 2. Merging Arrays const a = [1, 2]; const b = [3, 4]; const merged = [...a, ...b]; 3. Copying Objects const user = { name: "Ali", age: 20 }; const newUser = { ...user }; 4. Merging Objects const obj1 = { a: 1 }; const obj2 = { b: 2 }; const merged = { ...obj1, ...obj2 }; 5. Updating Object Values const user = { name: "Ali", age: 20 }; const updatedUser = { ...user, age: 21 }; 6. Passing Array as Function Arguments const nums = [1, 2, 3]; console.log(Math.max(...nums)); --- Rest Operator ("...") Definition: The rest operator is used to collect multiple elements into a single array. It “gathers” values. Common Use Cases: 1. Function Parameters (Unlimited Arguments) function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } 2. Collect Remaining Elements in Array Destructuring const [first, ...rest] = [1, 2, 3, 4]; console.log(rest); // [2, 3, 4] 3. Collect Remaining Properties in Objects const { name, ...others } = { name: "Ali", age: 20, city: "Lahore" }; console.log(others); // { age: 20, city: "Lahore" } --- Key Difference - Spread ("...") → Expands values - Rest ("...") → Collects values --- Simple Tip to Remember: - Spread = “Open / Expand” - Rest = “Collect / Gather” --- If you're learning JavaScript, mastering these will make your code cleaner and more powerful #JavaScript #WebDevelopment #Coding #Frontend #MERN #LearnToCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories