Javascript rest operator
Created By: chatGPT
JavaScript's Rest Operator allows you to represent an indefinite number of arguments as an array. This operator is particularly useful when you're working with functions and want to group parameters. The rest operator is denoted by three dots
...
followed by the name of the variable you want to create. Here's a brief example to illustrate how it works.function collectArgs(...args) {
return args;
}
console.log(collectArgs(1, 2, 3)); // Output: [1, 2, 3]
console.log(collectArgs('a', 'b', 'c', 'd')); // Output: ['a', 'b', 'c', 'd']
Combining Rest with Other Parameters is quite common. You can use the rest operator alongside named parameters. Any parameters listed before the rest operator will be assigned their respective values, while any additional arguments will be grouped into the rest variable, as shown below.
function userDetails(name, age, ...hobbies) {
return `Name: ${name}, Age: ${age}, Hobbies: ${hobbies.join(', ')}`;
}
console.log(userDetails('John', 30, 'reading', 'gaming', 'hiking')); // Output: Name: John, Age: 30, Hobbies: reading, gaming, hiking
Destructuring with Rest Operator can also be utilized to separate elements from an array or an object. This makes it easier to work with specific groups of values.
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5]
Functional Programming often involves callbacks and higher-order functions. The rest operator can be used to create functions that can accept a dynamic number of arguments, enhancing flexibility.
const multiply = (...args) => {
return args.reduce((acc, curr) => acc * curr, 1);
};
console.log(multiply(2, 3, 4)); // Output: 24
console.log(multiply(1, 5, 7, 9)); // Output: 315