Spread vs Rest Operators in JavaScript
In simple terms, the spread operator is used for expanding elements while the rest operator is used to collect multiple elements into an array. These operators have same syntax (...) but have different purposes.
Eg. In case of spread operator(spreading/expanding)
let a = [1,2,3,4,5]
let arr = [...a, 6,7]
console.log(arr) //output: [1,2,3,4,5,6,7]
the ...a spread operator expands the a array into individual elements, the code the logs the new array arr that contains the old elements and the new elements 6,7.
We can also merge arrays, let arr1 = [4, 5];
let arr2 = [6, 7];
let merged = [...arr1, ...arr2];
console.log(merged); //output: [4, 5, 6, 7]
When, const obj = {x:1, y:2}
const Obj = {y:3, z:4}
const updatedObj = {...obj, ...Obj}
console.log(updatedObj); //output: {x: 1, y: 3, z: 4}
...obj and ...Obj expand properties into a new object. Since y was written two times, it was overridden by the 2nd value of y.
In case of rest operator(collecting)
function example(...elems){
console.log(elems)
}
example('a', 'b', 'c'); // output: ['a', 'b', 'c']
...elems collects all the passed arguments into an array. When we called example('a', 'b', 'c') it printed an array as all the elements got grouped into an array.
Destructuring using rest operator:
First element is extracted and rest elements are gathered.
Eg. const [first, ...rest] = [20, 21, 22, 23];
console.log(first);
console.log(rest);
Output: 20
[21, 22, 23]
| Feature | Rest Operator | Spread Operator |
|---|---|---|
| Syntax | function(...args) {} | [...array], {...object} |
| Purpose | Collects multiple values into an array | Expands elements of an array or object |
| Usage | Function parameters, destructuring | Arrays, objects, function calls |
| Returns | Array | Individual element |
gather together(rest operator): 1 2 3 => [1,2,3]
take apart(spread operator): [1,2,3] => 1 2 3