What is the rest operator in JavaScript?
The rest operator is used to concatenate two arrays.
The rest operator is used to spread an array into individual elements.
The rest operator is used to represent a single argument as an array.
The rest operator is used to represent an indefinite number of arguments as an array.
The rest operator, denoted by three consecutive dots (...) before a parameter name in a function declaration or function expression, allows us to represent an indefinite number of arguments passed to a function as an array. This makes it easier to work with varying numbers of arguments within the function body. For example:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5)); // Output: 9
In the above code, the rest operator is used to capture all the arguments passed to the "sum" function and store them in the "numbers" array. The reduce method is then used to calculate the sum of all the numbers in the array.