0% completed
The Rest Parameter syntax in JavaScript allows a function to accept an indefinite number of arguments, providing a way to handle function parameters more flexibly. Introduced in ECMAScript 2015 (ES6), this feature enhances the capability to deal with multiple parameters without specifying each one individually in the function definition.
To declare a function using a rest parameter, use three dots (...
) followed by the name of the array that will contain all remaining arguments passed to the function.
map
, filter
, reduce
, etc.) can be directly applied.Explanation:
sum
is defined to take an arbitrary number of numeric arguments, grouped into an array called numbers
.[1, 2, 3, 4, 5]
to the console, showing how the rest parameter aggregates arguments.reduce
method is used to sum all elements in the numbers
array, starting from an initial sum of 0
.sum
is called with five numbers, it returns the sum of all these numbers, demonstrating the utility of rest parameters in handling a variable number of inputs effectively.Function Definition:
function processInfo(firstName, lastName, ...details) {...}
defines a function named processInfo
that requires two parameters, firstName
and lastName
, followed by a rest parameter details
.Logging Parameters:
console.log('First Name:', firstName);
logs the first argument as the first name.console.log('Last Name:', lastName);
logs the second argument as the last name.console.log('Details:', details);
logs any additional arguments as an array under 'Details'. This demonstrates how the rest parameter collects all remaining arguments beyond the first two.Function Call:
processInfo('John', 'Doe', 'Age: 30', 'Location: New York', 'Status: Active');
calls the processInfo
function with two fixed arguments for the name and three additional arguments that are grouped into the details
array.This example is particularly useful for functions where the initial arguments are essential for the primary operation, and the subsequent arguments are optional or numerous, requiring grouped handling. The rest parameters make the function flexible and capable of handling additional data without specifying each argument, enhancing code reusability and clarity.
Rest parameters are useful for several reasons:
arguments
object......
.....
.....