Rest Parameters
Default rest parameters allow you to specify default values for the rest of the parameters in a function declaration. Rest parameters gather all remaining arguments into an array, and default rest parameters provide default values for those arguments if no value or undefined is passed. This feature was introduced in ES6 (ECMAScript 2015). Here's how it works:
// Example without default rest parameters
function sum(x, y, z) {
return x + y + z;
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(1, 2)); // Output: NaN (Not a Number) because z is undefined
In the example above, if you don't pass a value for z
, it becomes undefined
, and the function returns NaN
because you're trying to add a number with undefined
.
Now, let's see how default rest parameters can help:
// Example with default rest parameters
function sumWithDefaults(x, y = 0, ...rest) {
let sum = x + y;
for (let val of rest) {
sum += val;
}
return sum;
}
console.log(sumWithDefaults(1, 2, 3)); // Output: 6
console.log(sumWithDefaults(1, 2)); // Output: 3 (because rest defaults to an empty array)
In this updated example, ...rest
is the rest parameter that gathers all remaining arguments into an array. Here, we set a default value of an empty array ([]
) for rest
. So if you don't pass any additional arguments beyond x
and y
, rest
will be an empty array, and the function will return the sum of x
and y
.
You can also have default rest parameters with initial values:
// Example with default rest parameters with initial values
function sumWithInitialValues(x, y = 0, ...rest) {
let sum = x + y;
for (let val of rest) {
sum += val;
}
return sum;
}
console.log(sumWithInitialValues(1, 2, 3, 4, 5)); // Output: 15
console.log(sumWithInitialValues(1)); // Output: 1 (because y defaults to 0 and rest defaults to an empty array)
In this example, y
has a default value of 0
, and rest
has a default value of an empty array. So if you don't provide any additional arguments beyond x
, y
will be 0
, and rest
will be an empty array.
Default rest parameters are particularly useful when you want to handle functions with a variable number of arguments and provide default values for those arguments.
Leave a Comment