Difference between spread and rest operators in javascript

Difference between spread and rest operators in javascript

·

6 min read

👉 Spread and Rest operator both uses ... three dots so should we consider them same❓

Not at all ..... They are completely different. So in this article, We are gonna learn about their differences and what they exactly do?
The main difference between spread and rest is spread converts packed items into individual items and rest operator puts rest of user-supplied value into an array .

What is spread operator?

The spread operator (...) helps you expand iterables into individual elements. Spread syntax (...) allows an iterable, such as an array or string, to be expanded in places where zero or more arguments basically in function calls are expected.
In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [6, 2, 3];

console.log(sum(...numbers));// spread operator
// output: 11

Now, We will understand the spread operator by seeing its use cases.

1. Spread in function calls

In the below example, we used the spreadsyntax to spread the numbers array’s content across add() parameters. Here the numbers array contains 5 items but the function will take 3 parameters and ignore the rest.

const numbers = [1, 3, 7, 10, 200];

function add(a, b, c) {
  return a + b + c ;
}


console.log(add(...numbers));  //11

2. Spread in array literals

a)Copy an array

Copying without spread operator

const cities = ["jaipur", "mumbai", "delhi" ];
const cities2 = cities; 
console.log(cities2);
//["jaipur", "mumbai", "delhi" ];

This works absolutely fine but problem arises when we add a new item in cities2 , the original array also changes which we doesn't want .


let newElement = cities2.push("chennai");
console.log(cities2);
console.log(cities);
["jaipur", "mumbai", "delhi", "chennai" ]
["jaipur", "mumbai", "delhi", "chennai" ]-> original array also changes

Using spread operator

const cities = ["jaipur", "mumbai", "delhi" ];
const cities2 = [...cities]; 

cities2.push("chennai");
//  cities2 becomes ["jaipur", "mumbai", "delhi", "chennai" ];
//  cities remains unaffected

b) Concatenation

without spread operator

let cities1 = ["jaipur", "mumbai", "delhi" ];
const cities2 = ["telangana", "amritsar", "chandigarh"];

cities1 = cities1.concat(cities2);

concat() method is often used to concatenate two or more arrays

Using spread operator

let cities1 = ["jaipur", "mumbai", "delhi" ];
const cities2 = ["telangana", "amritsar", "chandigarh"];

cities1 = [...cities1, ...cities2];

c)Convert a String into Individual Array Items:-

In the below example we used the spread syntax (...) within an array literal object ([...]) to expand myName’s string value into individual items.

const myName = "Muskan";

console.log([...myName]);

// The invocation above will return:
["M", "u", "s", "k", "a", "n"]

3. Spread in object literals

a) Merging an object

Like array , we can also merge two or more objects using spread operator.

const obj1 = { size:'23', loginCount: 42 };
const obj2 = { color: 'blue', isLoggedout:false };


const mergedObj = { ...obj1, ...obj2 };
//{ size:'23', loginCount: 42 ,color: 'blue', isLoggedout:false};

b) Cloning an object

We can use the spread operator to clone one object's properties into another but we can't expand its values as the properties object is not an iterable object.

const myName = 
{ 
firstName: "Muskan", 
lastName: "Bansal" 
};
const bio = { ...myName};
console.log(bio);
//{firstName: "Muskan", lastName: "Bansal" }

Note :-The spread operator does not clone identical properties.

For example:-

const myName = { firstName: "Muskan", lastName: "Bansal" };
const bio = { ...myName, firstName: "Arun", age:21 };

console.log(bio);
//{ firstName: "Arun", lastName: "Bansal", age:21 };

Observe that the spread operator did not copy myName’s firstName property into the bio objectbecause bio already contains the firstName property.

Now we have learned spread operator fully , Lets see the rest operator

What is Rest operator?

The rest operator is used to put the rest of some specific user-supplied values into a JavaScript array. We can pass the individual items to the function and convert them into an array of parameters.

//Passing  n number of arguments to a function and return the sum of it.
function add(...theArgs) {
  let sum = 0;
  for (const arg of theArgs) {
    sum += arg;
  }
  return sum;
}

console.log(add(1, 2, 3)); //6

A function definition's last parameter can be prefixed with ... which will cause all remaining parameters to be placed within a JavaScript array. Only the last parameter in a function definition can be a rest parameter. For example:-

function numbers(a,  b, ..aArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", args);
}
numbers(1,2,3,4,5,6);

// a, 1
// b, 2
// manyMoreArgs, [3,4,5,6]

In the above example , 1 and 2 are assigned to a and b and remaining parameters are assigned in args.

Note :-A function definition can have only one ...restParam.

❌foo(...one, ...wrong, ...wrong)

The rest parameter must be the last parameter in the function definition.

❌foo(...wrong, arg2, arg3)

It becomes handy when we need to pass the n number of arguments to a function and we are not sure about their number, the rest parameter makes it really easier to do the task.

Destructure object using rest parameter

const { firstName, lastName, ...otherInfo } = {
  firstName: "Muskan",
  lastName: "Bansal", 
   profession: "Web Developer",
  gender: "Female"
}


console.log(otherInfo);
//{ profession: "Web Developer", gender: Female"}

Observe that the rest operator assigned a properties object — not an array — to the otherInfo variable.

In simple words, whenever we use rest in a destructuring object, the rest operator will produce a properties object. However, if we use rest in a destructuring array or function, the operator will give an array literal.

Before we wrap our discussion I want to tell you some differences between arguments object and rest operator.

  • Arguments object is not a real array
    rest parameters are real arrays we can use methods like map(), sort(), pop() inside it but we can't use on arguments object.

  • We cannot use the arguments object in an arrow function
    The arguments object is not available within an arrow function, so we can’t use it there. But we can use the rest parameter within all functions — including the arrow function.

function multiply(multiplier, ...theArgs) {
  return theArgs.map((element) => multiplier * element);
}

const arr = multiply(2, 15, 25, 42);
console.log(arr); // [30, 50, 84]

Now, we have understood the rest & spread operators it's really easy to differentiate between these two.

Conclusion

...spread is used to expand iterables into individual elements. Whereas ...rest is used to condense the value into a JS array.

Thanks a ton for reading this article .i have researched about this a lot and it took me plenty of time but I have tried to explain it with simple examples. Hope you like it. Please share your thoughts and I hope that it saves your lot of time.

Â