loading...

JavaScript's Three Dots: Spread Operator vs. Rest Parameters

carriepascale profile image Carrie Pascale👩‍💻 Updated on ・2 min read

What is the difference between the spread operator and rest parameters, anyway? Aren't they the same thing? I thought so too, but they are pretty much opposites.

TL;DR: When you pass in arguments to a function using the spread operator, you are using rest parameter syntax.

The spread operator allows expressions to be expanded in places where multiple arguments, elements or variables are expected. In both cases below, the spread operator copies every element in the original array, and any elements that come afterward are pushed onto the end. I've also used the spread operator in solving a common interview question called Max Characters.

Copy an Array

Alt Text: An array called 'arr' has three elements: the numbers 1, 2, and 3. Set a variable called 'arrCopy' equal to [...arr, 4, 5], and it replaces the array method 'slice.' If you log out 'arrCopy', it includes the numbers 1, 2, 3, 4 and 5.

Concatenate an Array

Alt Text: If you have two arrays called 'arr' and 'arrTwo', you can concatenate them using the spread operator. Set 'arr' equal to [...arr, ...arrTwo], and 'arr' will include all the elements in both arrays in the order in which they are received.

Find the Most Frequent Character in a String

Alt Text: To solve Max Characters, create a character map of each character in a string, use spread syntax to find the max value in that map and finally, return the key at the maximum value.

Rest Parameters - You Can Use Array Methods!

Rest parameters condense elements into an array. You are using rest parameters if the three dots are being passed in as an argument into a function. In the below example:

  • Rest parameter syntax allows an unlimited number of arguments to be passed down to the multiply function.
  • Each time you will return an array with the same number of elements as the number of arguments passed in, minus one.
  • The values of each element will equal the original values multiplied by the first number.

Alt Text: Pass a number and '...args' as arguments to a function called multiply, and return args.map, where you multiply each element by the number. If you pass any number of numbers into this function, the first number will always be the multiplier and you will return an array with the same number of elements as the number of arguments passed in, minus one. The values of each element will equal the original values passed in, times the first number.

That's it! Now you know. 👋

Discussion

pic
Editor guide