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

Javascript Module 34

  Javascript Module 34 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test A...