What is the rest parameter and spread operator?
Both the rest parameter and spread operator are expressed in JavaScript code as ...
This might initially be confusing as they do opposite things.
Rest parameter: collects all remaining elements or arguments into an array.
Spread operator: allows iterables such as arrays, strings, or objects to be expanded into single arguments or elements.
Lets look at some examples to figure out what the above actually means.
Dive into the Rest Parameter
When defining functions in JavaScript, we can add parameters. Parameters describe arguments that will be supplied when calling the function. In the code below we have a function definition for a function puppy
that returns a description of a puppy. Name, breed and size are the function's parameters. Spot, Dachshund and small are the supplied arguments when the function is called.
function puppy(name, breed, size){
var description = `${name} is a ${size} ${breed}`
return description
}
puppy("Spot", "Dachshund", "small")
We can add another special kind of parameter to a function called the rest parameter. This parameter will take all the remaining arguments that are supplied and collect them into an array. Because it collects all remaining arguments it must be the last parameter provided in the function definition.
You can call it whatever you'd like to as long as you use the ...something
syntax. I am using ...traits
below. The puppy function now returns an updated description with the traits if they are provided.
function puppy(name, breed, size, ...traits){
console.log(traits)
var description = `${name} is a ${size} ${breed}.`
if (traits.length > 0) {
return `${description} They have the following traits: ${traits.join(', ')}`
}
return description
}
Now if we add more arguments when calling the function and console log traits
we will get the additional arguments as an array. If there are no additional arguments supplied, then traits
will be an empty array.
puppy("Spot", "Dachshund", "small", "playful", "intelligent", "energetic", "stubborn")
// traits will be logged as:
// `[ 'playful', 'intelligent', 'energetic', 'stubborn' ]`.
// the function will return:
// 'Spot is a small Dachshund. They have the following traits: playful, intelligent, energetic, stubborn'
puppy("Spot", "Dachshund", "small")
// traits will be logged as []
// the function will return:
// 'Spot is a small Dachshund.'
How is the rest operator different than the arguments
object?
When writing JavaScript functions we also have access to an arguments
object. The arguments object contains all arguments that are passed to a function. At first glance we might think that then there is no difference between
- passing in the rest parameter as the only parameter to a function and
- the arguments object
However, the benefit to using the rest parameter in this case is that the rest parameter returns an actual array instance. This means that we can use any array method on it directly. The arguments object is not a real array. Trying to call array methods on it will result in an error.
Using the arguments
object:
If we have a new function puppyTraits
and call it with some arguments we can log the arguments object to get all the arguments passed in. But if we try to use an array method directly on the object we get an error. We can get around this if we wanted to by using Array.from(arguments)
to turn the object into an array instance. However, this is unnecessary if we use the rest operator.
function puppyTraits(){
console.log(arguments)
return `This puppy has the following traits: ${arguments.join(', ')}`
}
puppyTraits("playful", "intelligent", "energetic", "stubborn")
// arguments will be logged as:
/* [Arguments] {
'0': 'playful',
'1': 'intelligent',
'2': 'energetic',
'3': 'stubborn' }
*/
// the function will not return as there will be an error:
// TypeError: arguments.join is not a function
Using the rest operator
The same function using a rest parameter instead of the arguments function. Since traits is now an array we can use any array method on it in our code!
function puppyTraits(...traits){
console.log(traits)
return `This puppy has the following traits: ${traits.join(', ')}`
}
puppyTraits("playful", "intelligent", "energetic", "stubborn")
// traits will be logged as:
// [ 'playful', 'intelligent', 'energetic', 'stubborn' ]
// the function will return:
// 'This puppy has the following traits: playful, intelligent, energetic, stubborn'
Hopefully you have come away with a better understanding of what the rest parameter does in JavaScript and some of its use cases. We will dive into the spread operator in Part 2!
If you have any questions, comments, or feedback - please let me know. Follow for new weekly posts about JavaScript, React, Python, and Django!
Top comments (1)
Well explained Angelika!