I remember being asked about the difference between the rest and spread operator and drawing a blank. I hadn't used the spread operator since I was in my bootcamp, and even on that occasion it seemed a bit glossed over.
So I wanted to address this knowledge gap by walking through the use and differences between the rest and spread operator.
It's easy to confuse the spread operator and the rest operator because their syntax is so similar.
Spread Operator: we can spread the content of an iterable into individual elements.
Note: An iterable is an object which can be looped over or iterated over with the help of a for loop. Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables
Let's look at the Spread Example:
const arr = ["My", "name", "is", "Melissa"]
const copyArr = [...arr]
console.log(copyArr)
console.log(...copyArr)
Let's see what the console returns when we console.log(copyArr)
We return ["My", "name", "is", "Melissa"]
The spread operator allows us unpack collected elements into their own single elements.
Rest: allows a function to accept an indefinite number of arguments as an array
Let's look at an example:
function logFullName(firstName, ...familyName) {
console.log(firstName);
console.log(familyName);
}
logFullName("Robert", "Alfred", "Cole");
**Update: thank you Bryce Dorn for correcting my code!
The elements of myName is being broken apart and reorganized into a new subarray. This is called destructuring, an array or object is broken into smaller pieces.
Let's look at our console:
The first console.log
of console.log(firstName)
returns the first element in the array, 'Robert'. The rest of the elements in the array are collected and put into a new sub array called familyName. This is why when we console.log(familyName)
we get the new sub array consisting of the rest of the original array ["Alfred", "Cole"]
.
Think of rest as a mnemonic device that means it creates its own collection of the rest of the array. In this example, that would be the new sub array ["Alfred", "Cole"]
.
**Update: Thanks to hacker4world for giving an example on the use and syntax with functions:
function logParams(...params) {
console.log(...params);
}
logParams(1, 2, 3, 4);
To further understand the logic at play, create your own examples and test them in your console of your choosing. Practicing this achieves a better understanding of rest and spread!