Since the invention of “…”, JavaScript has never been the same and is the one of the core functionalities of functional programming. The “…” can either be called spread or rest depending on where and how it is being used. Let’s look at specific examples of when to use a spread vs. rest operator in JavaScript.
Spread Operator (value…)
const animals = [ 🐕, 🐶, 🐢, 🐀, 🐸];
const someOtherAnimals = [...animals];
console.log(animals);
Within the given array, we have a list of animals. Similar to a box, the array just hold individual data types. The spread operator allows you to grab all of the contents of the box without having to “touch” the contents of the box.
Simple way to describe spread operators, is that they are used to copy the contents of animals into another array.
Rest Operator (…value)
The rest operator is used to put the rest of some specific user-supplied values into an array. The text after the rest operator references the values you wish to encase inside an array.
// Define a function with two regular parameters and one rest parameter:
function myBio(firstName, lastName, ...otherInfo) {
return otherInfo;
}
Explained simply, rest operators are usually used in functions and allow indefinite numbers of arguments as an array. A function definition can only have one rest parameter, and the rest parameter must be the last parameter.
Rest Operator in Objects
The rest operator typically get used as a prefix of the restructuring assignment’s last variable.
const [firstName, lastName, ...otherInfo] = [
"🐕",
"🐶",
"🐢",
"🐸",
];