Rest and Spread Operators
Rest Operator (`...`):
The rest operator (…) allows us to call a function with any number of arguments and then access those excess arguments as an array. The rest operator also allows us to destructure an array or objects.
1.Function Parameter:
The rest operator allows a function to accept an indefinite number of arguments as an array.
Example:
2. Destructuring:
The rest operator can be used to gather the remaining elements of an array or object.
Array Destructuring:
const [first, second, …rest] = [1, 2, 3, 4, 5];
console.log(rest); // Output: [3, 4, 5]
Object Destructuring:
const { name, age, …rest } = { name: ‘John’, age: 30, city: ‘New York’, country: ‘USA’ };
console.log(rest); // Output: { city: ‘New York’, country: ‘USA’ }
Spread Operator (`...`):
1.Array Spreading:
The spread operator is used to expand elements of an iterable (like an array) into another array or function argument.
Example:
const myArray = [1, 2, 3];
const newArray = […myArray, 4, 5];
console.log(newArray); // Output: [1, 2, 3, 4, 5]
2. Object Spreading:
The spread operator can be used to merge properties of objects or create a shallow copy.
Example:
const person = { name: ‘John’, age: 30 };
const details = { …person, city: ‘New York’ };
console.log(details);
// Output: { name: ‘John’, age: 30, city: ‘New York’ }
3. Function Argument:
The spread operator can be used to pass array elements as individual arguments to a function.
Example:
function multiply(a, b, c) {
return a * b * c;
}
const numbers = [2, 3, 4];
const result = multiply(…numbers);
console.log(result); // Output: 24
4. Clone Array:
Create a shallow copy of an array using the spread operator.
Example:
const originalArray = [1, 2, 3];
const copyArray = […originalArray];
console.log(copyArray); // Output: [1, 2, 3]
Key Points:
– The rest operator is used in function parameters or destructuring to collect elements.
– The spread operator is used to expand elements into arrays, objects, or function arguments.
– Both operators use the same syntax (`…`), but their usage and context differ.
Course Video
Examples for Practice
You have to solve all the questions given below in the editor without copy-pasting.
1. Write a function sumNumbers that takes any number of arguments and returns their sum using the rest operator.
The task is to write a JavaScript function called sumNumbers that takes any number of arguments and returns their sum using the rest operator.
1. Function Definition: Define a function called sumNumbers.
2. Use Rest Operator: In the function parameter list, use the rest operator (…) followed by a variable name (commonly named numbers or any name you choose). This allows the function to accept any number of arguments and stores them in an array called numbers.
3. Calculate Sum: Use array methods (e.g., reduce, forEach) or a simple loop to iterate over the array of numbers and calculate their sum.
4. Return Result: Return the calculated sum.
Here’s an example program:
// Step 1: Define the function sumNumbers
function sumNumbers(…numbers) {
// Step 2: Use the Rest Operator to store arguments in an array called numbers
// Step 3: Calculate the sum using array methods or a loop
const totalSum = numbers.reduce((sum, num) => sum + num, 0);
// Step 4: Return the calculated sum
return totalSum;
}
// Example usage
const result = sumNumbers(5, 10, 15, 20);
console.log(“Sum:”, result); // Output: Sum: 50
Output
2. Create a function mergeArrays that takes two arrays as parameters and returns a new array containing elements from both arrays using the spread operator.
The task is to create a JavaScript function called mergeArrays that takes two arrays as parameters and returns a new array containing elements from both arrays using the spread operator.
1. Function Definition: Define a function called mergeArrays that takes two arrays as parameters.
2. Use Spread Operator: Inside the function, use the spread operator (…) to spread the elements of both arrays into a new array.
3. Return Result: Return the newly created array containing elements from both input arrays.
Here’s an example program:
// Step 1: Define the function mergeArrays
function mergeArrays(array1, array2) {
// Step 2: Use the Spread Operator to merge elements from both arrays
const mergedArray = […array1, …array2];
// Step 3: Return the merged array
return mergedArray;
}
// Example usage
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const result = mergeArrays(array1, array2);
console.log(“Merged Array:”, result); // Output: Merged Array: [1, 2, 3, 4, 5, 6]
Output
3. Create a function multiplyByFactor that takes a factor and any number of values as parameters. Multiply each value by the factor and return the results in an array using the rest and spread operators.
The task is to create a JavaScript function called multiplyByFactor that takes a factor and any number of values as parameters. The function should multiply each value by the factor and return the results in an array using the rest and spread operators.
1. Function Definition: Define a function called multiplyByFactor that takes the factor and any number of values as parameters using the rest operator (…).
2. Use Spread Operator: Inside the function, use the spread operator (…) to spread the values into an array.
3. Multiply Each Value: Use array methods or a loop to multiply each value by the provided factor.
4. Return Result: Return the array containing the results of multiplying each value by the factor.
Here’s an example program:
// Step 1: Define the function multiplyByFactor
function multiplyByFactor(factor, …values) {
// Step 2: Use the Spread Operator to spread values into an array
// Step 3: Multiply each value by the factor
const results = values.map(value => value * factor);
// Step 4: Return the array containing the results
return results;
}
// Example usage
const factor = 2;
const multipliedValues = multiplyByFactor(factor, 3, 5, 7);
console.log(“Multiplied Values:”, multipliedValues); // Output: Multiplied Values: [6, 10, 14]
Output
4. Write a function filterOddNumbers that takes an array of numbers as a parameter and returns a new array containing only the odd numbers using the rest and spread operators.
The task is to write a JavaScript function called filterOddNumbers that takes an array of numbers as a parameter and returns a new array containing only the odd numbers using the rest and spread operators.
1. Function Definition: Define a function called filterOddNumbers that takes an array of numbers as a parameter using the rest operator (…).
2. Use Spread Operator: Inside the function, use the spread operator (…) to spread the array of numbers into a new array.
3. Filter Odd Numbers: Use array methods (e.g., filter) to create a new array containing only the odd numbers.
4. Return Result: Return the array containing only the odd numbers.
Here’s an example program:
// Step 1: Define the function filterOddNumbers
function filterOddNumbers(…numbers) {
// Step 2: Use the Spread Operator to spread numbers into an array
// Step 3: Filter only the odd numbers
const oddNumbers = numbers.filter(number => number % 2 !== 0);
// Step 4: Return the array containing only the odd numbers
return oddNumbers;
}
// Example usage
const inputNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filteredOddNumbers = filterOddNumbers(…inputNumbers);
console.log(“Filtered Odd Numbers:”, filteredOddNumbers);
// Output: Filtered Odd Numbers: [1, 3, 5, 7, 9]
Output
5. Create a function that takes a variable number of arguments using the rest parameter. Inside the function, use the spread operator to concatenate these arguments into a single array. Then, operate on each element of the array (e.g., multiply by 2) and return the modified array.
The task is to create a JavaScript function that takes a variable number of arguments using the rest parameter concatenates these arguments into a single array using the spread operator, operates on each element of the array, and finally returns the modified array.
1. Function Definition: Define a function that uses the rest parameter (`…`) to accept a variable number of arguments.
2. Use Spread Operator: Inside the function, use the spread operator (`…`) to concatenate these arguments into a single array.
3. Operate on Each Element: Use array methods or a loop to operate on each element of the array (e.g., multiply by 2).
4. Return Modified Array: Return the modified array.
Here’s an example program:
// Step 1: Define the function operateOnElements
function operateOnElements(…args) {
// Step 2: Use the Spread Operator to concatenate arguments into an array
// Step 3: Operate on each element (e.g., multiply by 2)
const modifiedArray = args.map(element => element * 2);
// Step 4: Return the modified array
return modifiedArray;
}
// Example usage
const result = operateOnElements(1, 2, 3, 4, 5);
console.log(“Modified Array:”, result);
// Output: Modified Array: [2, 4, 6, 8, 10]
Output