Monday, June 23, 2025

Javascript Module 15

   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

“AI Analytics Dashboard with Python: The Secret Data Science Technique That Predicts Trends and Boosts Business Intelligence”

  Discover the power of AI Analytics Dashboards with Python and learn how to transform raw data into powerful insights that can predict tren...