DEV Community

Anuj Srivastav
Anuj Srivastav

Posted on

Javascript Rest vs Spread Operator - What's the difference?

In JavaScript, the rest and spread operators are both denoted by the same three dots (...) syntax, but they are used in different contexts and have different effects.

The rest operator is used in a function's parameter list to represent an indefinite number of arguments passed to the function. It allows you to pass a variable number of arguments to a function and handle them as an array inside the function. Here's an example:

function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3)); // output: 6

Enter fullscreen mode Exit fullscreen mode

In this example, the ...numbers parameter in the sum function's parameter list represents an indefinite number of arguments that can be passed to the function. The rest operator collects all the arguments into an array called numbers.

On the other hand, the spread operator is used to spread the elements of an iterable (such as an array) into another iterable (such as an array or an object). Here's an example:

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

console.log(arr2); // output: [4, 5, 1, 2, 3]

Enter fullscreen mode Exit fullscreen mode

In this example, the spread operator (...arr1) is used to spread the elements of arr1 into arr2. This results in a new array (arr2) that contains all the elements of arr1 followed by 4 and 5.

In summary, the rest operator is used to collect a variable number of arguments into an array in a function's parameter list, while the spread operator is used to spread the elements of an iterable into another iterable.

The main difference between two is -

  • The rest operator is used to fill a JavaScript array
    with the remaining data from a user.

  • The JavaScript spread operator allows an array or an
    object to be spread or flattened into its elements.

In common terms We can say -

  • Rest we use for pack elements.

  • Spread we use for unpack elements.

Top comments (0)