DEV Community

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

Posted on • Edited 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)