In short we could say that:
- spread operator unpacks elements.
- rest parameter packs elements.
argument— An argument is a value passed to a function.
parameter— A Parameter is a variable used in the declaration of a function.
iterable— A collection of something that we can iterate (loop) over. For example array, list, set, and string.
The spread operator unpacks iterables into individual elements. Let’s look into different scenarios when this is useful.
The spread operator unpacks an array into separate arguments:
const array = [1, 2, 3];
// -> 1 2 3
This comes in handy when a function expects a list of arguments and all you have is an array:
const array = [4, 2, 9, 5];
Math.max(…array); // -> 9
To copy an array we put the spread values into another array:
This is a great way of cloning arrays. If we do changes to either of the arrays they will not affect the other.
The spread syntax can also be used to compose several values into one:
This is useful when we want to add elements into an existing array. We can even merge two arrays:
These operations are not only available for arrays but also other iterables like strings:
The spread operator (…) with objects is used to create copies of existing objects with new or updated values or to make a copy of an object with more properties. Let’s take an example of how to use the spread operator on an object.
Here we are spreading the
user object. All key-value pairs are copied into the
The spread syntax is useful for merging the properties and methods on objects into a new object:
Note: Spread syntax only does a shallow copy meaning nested arrays or objects will not copy properly. The deeper data is still linked to the original.
Where the spread operator unpacks the contents of an iterable into single elements, the rest parameter instead collects all the remaining elements into an array.
We can use the rest parameter when we don’t know how many arguments will be used or just want to collect some of them into an array.
Let’s try an example where we add together all the values sent into our function:
So, no matter how many numbers we send into the
sum function they will be added together.
Let’s do another example:
As shown in the above example, the three dots collected all the elements after the
spouse into the
We can also use the rest syntax with objects together with destructuring:
Note: Rest parameters have to be the last argument. This is because it collects all remaining arguments into an array.
- Rest Parameter collects all remaining elements into an array.
- Spread Operator expands collected elements such as arrays into single elements.
- The spread syntax only does a shallow copy one level deep.
- Only the last parameter can be a rest parameter.
Getting Started Series