Rest parameter vs Spread Operator in JavaScript?

The rest parameter and spread operator are two related features in JavaScript. The rest parameter allows you to represent an indefinite number of arguments as an array, while the spread operator allows you to expand an array into individual arguments.

Rest Parameter

The rest parameter is denoted by three dots followed by a parameter name. It allows you to represent an indefinite number of arguments as an array. This can be useful when you don’t know how many arguments a function will receive, or when you want to allow a variable number of arguments.

Here’s an example of using the rest parameter in a function that calculates the sum of an arbitrary number of numbers:

function sum(...numbers) {

  return numbers.reduce((prev, current)  =>  prev+ current, 0 );
}

console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5, 6, 7)); // Output: 22


In this example, the sum function takes any number of arguments and uses the reduce method to add them all up. The …numbers syntax tells JavaScript to gather all of the arguments into an array called numbers and then uses the reduce method to sum all arguments.

Spread Operator

The spread operator is also denoted by three dots , but it is used in a different context. It allows you to expand an array into individual arguments. This can be useful when you want to pass the elements of an array as arguments to a function.

Here’s an example of using the spread operator to pass the elements of an array as arguments to a function:

const numbers = [1, 2, 3];
console.log(...numbers); // Output: 1 2 3


In this example, the …numbers syntax tells JavaScript to expand the numbers array into individual arguments. The console.log function then receives these arguments as separate values.

Here is another example of using the spread operator:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];

console.log(combined); // Output: [1, 2, 3, 4, 5, 6]


In this example, the …arr1 and …arr2 syntax tells JavaScript to expand the two arrays into individual elements. These elements are then combined into a new array we decleared called combined using the array spread syntax […].


Happy Learning …