Difference between Spread and Rest operator

Difference between Spread and Rest operator

If we take a look at both spread and rest operators they both look the same as they use the same syntax as 3 dots (...) in front of them and because of this it causes confusion among beginners.

So let's find the difference between them.

Spread Operator

Spread operator as the name suggests spreads the elements from an array, object, or string. It unpacks or expands all the elements at once.

For example, here let's take an array (arr) and try to spread it using the spread operator within another array and console logging the value.

const arr = [7, 8, 9];
console.log([1, 2, ...arr]);
// [1, 2, 7, 8, 9]

How does it make our code more understandable and cleaner, Why do we need it? Let's try to understand with another example. Suppose we want to combine two arrays.

If not for the spread operator one way would be to manually put each array element which obviously is a bad practice. And another would be by using a loop which again would need many lines of code.

//Bad Practice

//Manually putting values in array
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

console.log([arr1[0], arr1[1], arr1[2], arr2[0], arr2[1], arr2[2]]);
// [1, 2, 3, 4, 5, 6]


// With loops
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
let array = [];

for(let i = 0; i < array1.length; i++){
array.push(array1[i]);
}
for(let j = 0; j < array2.length; j++){
array.push(array2[j]);
}

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

Now, with the spread operator.

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

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

So as you can see we can get the same result in one line without much hassle and our code looks much cleaner. The Spread operator splits the array into individual elements separated by commas. Some other examples with spread operator.

Spread operator with strings

const message = "Hello";
console.log([...message]);
//['H', 'e', 'l', 'l', 'o']

Spread operator with object literals

const details ={
    occupation: "Engineer",
    city: "America"
}

const person = {
    name: "Jonas",
    age: 30,
    ...details
};

console.log(person);
//{name: 'Jonas', age: 30, occupation: 'Engineer', city: 'America'}

Spread operator with Function arguments

const persons = ["Chandler", "Joey", "Ross"];

const details = (person1, person2, person3) => `My friends are ${person1}, ${person2}, and ${person3}`

details(...persons);
//'My friends are Chandler, Joey, and Ross'

Rest Operator

The rest operator gathers all elements in the array. Also, it helps to pass an infinite number of function arguments. It is just the opposite of the spread operator. Understanding rest operator with an example.

const example = (first, second, ...others) => {
    console.log(first); 
    console.log(second); 
    console.log(others); 
};
example(1, 2, 1, 4, 5);
// 1
// 2
// [1, 4, 5]

As you can see except for the first and second arguments all the rest arguments go inside the others parameter. So rest operator groups together the remaining elements into an array.

If first and second parameters weren't present then it would have put all the values inside other parameter.

Also, the rest operator must always be the last argument passed otherwise will give a Syntax error.

//Bad Practice

const example = (first, ...others, last) => {
    console.log(first);
    console.log(others);
    console.log(last);
};
example(1, 2, 1, 4, 5);
// SyntaxError: Rest parameter must be last formal parameter

Some other examples of rest operators.

Rest operator in destructuring

const myObj = {apples: 2, oranges: 5, mangoes: 6, watermelons: 1, cherries: 3};
const { apples, oranges, ...other } = myObj;

console.log(apples); // 2
console.log(oranges); // 5
console.log(other); // { mangoes: 6, watermelons: 1, cherries: 3 }

Rest operator with function

const add = (...number) => {
  let sum = 0;
  for (let num of number) {
    sum += num;
  }
  return sum;
}

console.log(add(8, 6, 5, 1)); 
// 20

Conclusion

  • Although both the spread operator and the rest operator look the same their work is totally opposite to each other. The spread operator spreads an array, object, or string into individual elements whereas the rest operator gathers the elements into an array.

  • The rest operator must always be the last parameter in the function definition, while the spread operator can be used in any position in an array or object.