Rest Parameters


Rest Parameters (ES6+): Gathering an indefinite number of arguments into an array. (...args).

Rest parameters allow a function to accept an indefinite number of arguments as an array. This provides a more readable and clean way to handle variadic functions compared to the arguments object.


Example 1: Basic Summation

// This function calculates the sum of all numbers passed to it.
function sumAll(...numbers) {
  // 'numbers' is an array containing all arguments.
  return numbers.reduce((acc, current) => acc + current, 0);
}

console.log(sumAll(1, 2, 3)); // Expected output: 6
console.log(sumAll(10, 20, 30, 40)); // Expected output: 100

Explanation

The ...numbers syntax gathers all arguments passed to the sumAll function into an array named numbers. The reduce method then iterates over this array to calculate the total sum.


Example 2: Combining Regular and Rest Parameters

// This function multiplies a base number by the rest of the numbers.
function multiply(multiplier, ...theArgs) {
  // 'theArgs' is an array of numbers to be multiplied.
  return theArgs.map((element) => multiplier * element);
}

let arr = multiply(2, 1, 2, 3);
console.log(arr); // Expected output: [2, 4, 6]

Explanation

The first argument 2 is assigned to the multiplier parameter. The rest parameter ...theArgs collects the remaining arguments (1, 2, 3) into an array, which is then used by the map function.


Example 3: Dynamic Logging Function

// This function logs a message with a specific type and additional details.
function logMessage(type, ...messages) {
  // 'messages' captures all details to be logged.
  console.log(`[${type}]`, ...messages);
}

logMessage("INFO", "User logged in", "ID: 123"); // Expected output: [INFO] User logged in ID: 123

Explanation

This example demonstrates how rest parameters can create flexible functions. The logMessage function requires a type, and ...messages gathers all subsequent strings into an array for logging.


Example 4: Checking for Element Existence

// This function checks if a collection contains a specific item.
function includes(firstElement, ...searchElements) {
  // 'searchElements' is an array of items to check for.
  return searchElements.includes(firstElement);
}

console.log(includes("apple", "banana", "mango", "apple")); // Expected output: true

Explanation

The ...searchElements syntax collects all arguments after the firstElement into an array. The includes array method then efficiently checks if firstElement exists within that collected array.


Example 5: Merging Objects

// This function merges multiple objects into one.
function mergeObjects(...objects) {
  // 'objects' is an array of all the source objects.
  return objects.reduce((merged, current) => ({ ...merged, ...current }), {});
}

const obj1 = { name: "John" };
const obj2 = { age: 30 };
const obj3 = { city: "New York" };
console.log(mergeObjects(obj1, obj2, obj3)); // Expected output: { name: 'John', age: 30, city: 'New York' }

Explanation

The ...objects rest parameter gathers all object arguments into an array. We then use the reduce method, employing the spread operator (...) to merge the properties of each object into a single new object.


Example 6: Function Argument Validation

// This function ensures all provided arguments are of a specific type.
function checkTypes(type, ...values) {
    // 'values' will be an array of arguments to type-check.
    return values.every(value => typeof value === type);
}

console.log(checkTypes("string", "hello", "world")); // Expected output: true
console.log(checkTypes("number", 1, 2, "3")); // Expected output: false

Explanation

The first argument specifies the expected type. The ...values rest parameter collects all subsequent arguments, and the every method checks if each one matches the specified type.


Example 7: Dynamic Class Instantiation

// A class representing a product.
class Product {
  constructor(...ingredients) {
    // 'ingredients' is an array of all ingredients for the product.
    this.ingredients = ingredients;
  }
}

const myProduct = new Product("flour", "sugar", "eggs");
console.log(myProduct.ingredients); // Expected output: ['flour', 'sugar', 'eggs']

Explanation

The constructor of the Product class uses a rest parameter ...ingredients to accept any number of ingredient strings. This allows for flexible product creation with varying ingredient lists.