Module 15 : Rest and Spread Operators.
๐ 1. Introduction to Rest and Spread Operators
๐น Syntax:
Both use three dots ... (ellipsis), but their meaning differs based on context:
Operator
Purpose
Context
...rest
Collects multiple elements into one
Function parameters
...spread
Spreads an iterable into individual elements
Arrays, objects, function calls
๐ 2. REST Operator (Collect)
✅ Definition:
The rest operator gathers multiple arguments into a single array.
javascript
code
function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0); } console.log(sum(1, 2, 3, 4)); // Output: 10
๐ Explanation:
...numbers collects all arguments into an array named numbers.
reduce() performs a cumulative sum.
⚙ Use Cases:
Handling variable number of parameters.
Extracting remaining values from an array/object.
๐ง Example:
javascript
code
function introduce(name, age, ...hobbies) { console.log(`Name: ${name}, Age: ${age}`); console.log(`Hobbies: ${hobbies.join(', ')}`); } introduce('Ali', 25, 'Reading', 'Gaming', 'Coding');
Output:
yaml
code
Name: Ali, Age: 25
Hobbies: Reading, Gaming, Coding
๐ 3. SPREAD Operator (Expand)
✅ Definition:
The spread operator expands elements of an array or object.
๐ Array Example:
javascript
code
const fruits = ['apple', 'banana']; const moreFruits = ['grape', ...fruits, 'orange']; console.log(moreFruits); // ['grape', 'apple', 'banana', 'orange']
๐ Function Arguments Example:
javascript
code
function multiply(a, b, c) { return a * b * c; } const nums = [2, 3, 4]; console.log(multiply(...nums)); // Output: 24
๐ Object Cloning Example:
javascript
code
const person = { name: 'Aisha', age: 28 }; const clone = { ...person }; console.log(clone); // { name: 'Aisha', age: 28 }
๐ 4. Combined Use of Rest and Spread
Example: Array Destructuring
javascript
code
const [first, ...rest] = [10, 20, 30, 40]; console.log(first); // 10 console.log(rest); // [20, 30, 40]
Example: Object Destructuring
javascript
code
const { a, ...rest } = { a: 1, b: 2, c: 3 }; console.log(a); // 1 console.log(rest); // { b: 2, c: 3 }
๐ฌ 5. Building a Dynamic Shopping Cart
๐ Objective:
Use rest and spread operators to build a flexible shopping cart system.
๐ป Code:
javascript
code
function addToCart(...items) { return [...items]; } let cart = addToCart('Book', 'Pen', 'Laptop'); console.log("Initial Cart:", cart); let updatedCart = [...cart, 'Mouse', 'Keyboard']; console.log("Updated Cart:", updatedCart);
๐งช Explanation:
addToCart(...items) uses the rest operator to collect input.
updatedCart = [...cart, ...] uses the spread operator to add items while maintaining immutability.
๐ Output:
less
code
Initial Cart: [ 'Book', 'Pen', 'Laptop' ]
Updated Cart: [ 'Book', 'Pen', 'Laptop', 'Mouse', 'Keyboard' ]
๐ง 6. Insights
๐ฌ Summary:
Study/Source
Finding
Mozilla Dev Docs
Rest and Spread are syntactic sugar for cleaner, more flexible code
V8 Engine Benchmark
Spread operator is marginally slower for large arrays than Array.prototype.concat due to memory copy overhead
Airbnb JavaScript Style Guide
Recommends spread for immutability and clarity in object manipulation
๐ Observations:
Performance Consideration: Spread is easier to read but can be slower in massive datasets.
Readability: Spread improves code clarity over traditional loops and Object.assign().
๐งฉ 7. Exercises
๐ธ Exercise 1: Function Rest Parameters
Write a function logMessages that can accept any number of string messages and log them individually.
javascript
code
function logMessages(...messages) { messages.forEach(msg => console.log(msg)); } logMessages("Hello", "World", "This", "Is", "JavaScript");
๐ธ Exercise 2: Merging Objects
Merge two objects userDetails and contactInfo using spread operator.
javascript
code
const userDetails = { name: "Sara", age: 22 }; const contactInfo = { email: "sara@example.com", phone: "1234567890" }; const completeProfile = { ...userDetails, ...contactInfo }; console.log(completeProfile);
๐ธ Exercise 3: Cloning with Modification
Clone the following array and add "Python" without modifying the original array:
javascript
code
const languages = ["JavaScript", "C++"]; const newLanguages = [...languages, "Python"]; console.log(newLanguages);
๐ 8. Quiz Section
Q1: What will be the output of this code?
javascript
code
const [x, ...y] = [1, 2, 3, 4]; console.log(x, y);
A) 1, [2, 3, 4]
B) [1], 2, 3, 4
C) Error
✅ Answer: A
๐ 9. Conclusion
๐ Key Takeaways:
Use rest when you're collecting arguments.
Use spread when you're expanding data.
Both are essential for writing clean, immutable, and flexible code in JavaScript.
๐ 10. Practice
Create a function registerUser that takes fixed fields username, email, and variable skills. Return a user object:
javascript code
function registerUser(username, email, ...skills) { return { username, email, skills: [...skills] }; } const user = registerUser("Farhan", "farhan@example.com", "HTML", "CSS", "JS"); console.log(user);
No comments:
Post a Comment