DEV Community

Muzammil
Muzammil

Posted on

Is "..." in javascript a spread operator or are they rest parameters?

Short answer? They're both. Here's to another question that choked up an interview process recently. Every time we come across the three dots in our javascript code, either it makes our life look so easy or it's another day of googling "Spread operator". Just remember the two points below if you're looking for a TL;DR or continue reading if you want to dig deeper.

Keep in mind:-

  1. The three dots (...) act as rest parameters if we aren't sure of the number of parameters in a function

  2. The three dots (...) act as spread operator when we have to merge two or more objects.

Rest Parameters

const sumOfAllArgs(...args){
 let result = 0;
 args.forEach((arg) => {
     result += arg;
 })
 return result
}

sumOfAllArgs(1,2,3,4,5) // would return 15
Enter fullscreen mode Exit fullscreen mode

The above function which uses the rest parameters doesn't have a limit on the number of arguments to be passed to it.

Spread Operator

When you need to unpack an array or join an array with another or in case of copying the values of an array to another we can use the same operator (...) for a different cause

Concatenating an array

const myArr = ["jack", "jill", "hill"]
const yourArr = ["water", ...myArr]
Enter fullscreen mode Exit fullscreen mode

Here the value of "yourArr" would be ["water", "jack", "jill", "hill"].

Copying arrays

const a1 = [1, 2, 3]
const a2 = [...a1]
Enter fullscreen mode Exit fullscreen mode

Any changes made to a1 wont affect array a2.

The spread operator can also be used to perform the same actions on objects as well. Hope you get it right the next time! :)

Top comments (0)