JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

What is the difference between spread and rest operator in JavaScript?

The main difference between the spread operator and the rest parameter is that the spread operator spreads out the elements of an iterable. In contrast, the rest parameter puts multiple function arguments into an array.

let arr1 = [1, 2, 3, 4];
let arr2 = [5, 6, 7];

let arr = [...arr1, ...arr2];
console.log(arr); //[1, 2, 3, 4, 5, 6, 7]

In this example, you can see that the spread operator has unpacked all the elements of arr1 and arr2.

function display(a, b, c, ...arr){
  console.log(a);
  console.log(b);
  console.log(c);
  console.log(arr);
}
display(1, 2, 3, 4, 5, 6, 7, 8);

Output

1
2
3
[4, 5, 6, 7, 8]

In this example, the rest parameter has collected arguments 4, 5, 6, 7, and 8 into an array arr.

Another difference is that the spread operator is used in function invocations, whereas the rest parameter is used as a function parameter.

function sum(a, b, c){
  return a + b + c;
}
let arr = [1, 2, 3];
let addition = sum(...arr);
console.log(`Sum is ${addition}`); //Sum is 6

In this example, an array is passed to the sum() function using the spread operator.

function show(...arr){
  console.log(arr);
}
show(1, 2, 3);

Output

[1, 2, 3]

Note: Apart from using the spread operator in function invocation, it is also used in merging arrays, copying arrays, and splitting a string into individual characters.

Lastly, the rest parameter must be the function's last parameter. On the other hand, you can use the spread operator anywhere in the function call.

Recommended Posts