Spread vs Rest
Explore the differences between the spread operator and rest parameter in JavaScript. Understand how to unpack arrays and objects with spread, and collect multiple function arguments using rest. Gain practical knowledge for handling iterables and using these ES6+ features effectively.
We'll cover the following...
JavaScript version ES6 (ES2015) brought us a couple of useful features for arrays represented by three dots ..., the rest parameter and the spread operator. ES2018 introduced the same syntax for objects.
It can be confusing to have one syntax represent two different uses. In this lesson, we will try to clear up the confusion and break down the two ways of using JavaScript’s three dots.
In short, we can say that:
- The spread operator unpacks elements.
- The rest parameter packs elements.
Definitions
-
argument– An argument is a value passed to a function. -
parameter– A parameter is a variable used in the declaration of a function. -
iterable– An iterable is a collection of something that we can iterate (loop) over, including arrays, lists, sets, and strings.
function print(params) {
params.forEach(param => console.log(param));
}
print(['arg1', 'arg2']);
// -> arg1
// -> arg2
Spread operator
The ...