DEV Community

Cover image for Spread operator vs Rest Operator (Parameters)
Shehraz arain
Shehraz arain

Posted on • Updated on

 

Spread operator vs Rest Operator (Parameters)

Remember: Spread Operator and Rest operator are the same when you look, just three dots ... But use differently.

Spread Operator:

Three dots ... Used to spread up array elements OR object properties.

For Example

We have an old array and we want to add all the elements from that old array to a new array three dots simply pull outs all the elements and add them to the new array which we created with square brackets and of course then we can add more elements to it.

const old_array = [1,2,3,4];
console.log([...old_array, 5]);
Enter fullscreen mode Exit fullscreen mode
output:
[1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

Spread operator used same it for the object we create a new object with curly braces with the age property but then we also have dot dot dot old_object means to pull out all the properties of the old object and their values and add them as a key value.

const old_object = {
  name: 'sheraz',
}
console.log({...old_object, age: 21});
Enter fullscreen mode Exit fullscreen mode
output
{name: 'sheraz', age: 21}
Enter fullscreen mode Exit fullscreen mode

Rest parameter:

Rest operator or Parameter is the same operator as a spread operator but used differently, Used of merge a list of function arguments into the array.
args received an unlimited amount of arguments, so 1 args,2,3, or whatever, we received more than one and they will merge all be merged together into an array. So we can apply the array method to our argument list or do whatever we want.

const args = [1,2,3];
const filter = (...args) => {
   return args.filter((el) => el === 1);
};
console.log(filter(...args));
Enter fullscreen mode Exit fullscreen mode
output:
[1]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Top Posts from the React Ecosystem

1. Changes In The Official React Documentation

The former React Docs Beta has been officially released as the updated React documentation at react.dev after years of hard work and refinement. Check out the brand new React Docs: What’s New in the Updated React Docs

2. CRA's Time is Over

React developer team has removed create-react-app (CRA) from official documentation rendering it no longer the default setup method for new projects. The bulky setup, slow, and outdated nature of CRA led to its removal: create-react-app is officially dead

3. How to Fetch Dev.to Articles for Your Portfolio

Integrate the articles of your Dev.to profile into your personal portfolio with either React, Vue, or Next.js by following these simple steps. It outlines how to include frontend to pull the information and correctly utilizes the Dev.to API: How to Fetch Your Dev.to Articles for Your Portfolio with React