JavaScript Spread vs Rest Operator With Examples
27 March, 2023
23
23
5
Contributors
ES6 has introduced two handy operators to developers called spread
and rest
. Interestingly enough, both operators use the same syntax ...
(yes, three dots) but provide entirely opposite outcomes.
This show will teach you about the spread and rest in JavaScript with examples and use cases. As you learn, please practice and create your own examples, and if you do so, share your learning with us in the comment below.
Alright, let's get started π
The Spread Operator
The spread
operator expands(spreads out) the individual elements of an iterable like strings or arrays. It is also handy in expanding an object and copying its enumerable properties to a new object.
There are plenty of use cases for the spread operator. Let us learn them with examples:
Cloning Objects and Arrays
You can clone an object or array using the spread operator to create a copy of them.
Let's take this employee
object,
const employee = {
'name': 'Bob',
'address': 'California',
'age': 23
}
Create a copy of this object using the spread
operator:
const clonedEmployee = {...employee}
console.log(clonedEmployee); // {name: 'Bob', address: 'California', age: 23}
employee === clonedEmployee; // false
It creates a clone of the employee
object. However, the cloned object is different from the actual employee object.
Similarly, for arrays:
const numbers = [1, 2, 3]
const cloned = [...numbers];
console.log(cloned); // [1, 2, 3]
numbers === cloned; // false
Combining Two Objects
We can use the spread
operator to combine two objects and create a new merged object. Please note the spread operator performs a shallow merge
. It means that the common properties of the first object will be overwritten with the values of the second object.
Let us take two objects employee
and salary
.
const employee = {
'id': "001",
'name': 'Bob',
'address': 'California',
'age': 23
}
const salary = {
'id': "001",
"amount": "200K",
"currency": "USD"
}
Now, let us create a combined object by merging these two objects using the spread
operator.
const merged = {...employee, ...salary};
console.log(merged);
The output will be a new merged object. Also, note that the id
property is not repeated twice in the merged object due to the shallow merging.
{
"id": "001",
"name": "Bob",
"address": "California",
"age": 23,
"amount": "200K",
"currency": "USD"
}
Adding New Properties to the Object
You can add a new property to the object using the spread
operator. It creates a new object with the additional property where the actual object remains unchanged.
const employee = {
'name': 'Bob',
'address': 'California',
'age': 23
}
const empWithDept = {...employee, 'dept': 'Finance'};
console.log(empWithDept); // {name: 'Bob', address: 'California', age: 23, dept: 'Finance'}
console.log(employee); // {name: 'Bob', address: 'California', age: 23}
In the example above, we added a new property dept
with its value to the employee object. Also, notice that the employee object remains unchanged.
Update Properties of Objects
Similar to adding a new property, you can also update the value of an existing object property. Here also, the original object remains unchanged, and a new object gets created with the update.
const employee = {
'name': 'Bob',
'address': 'California',
'age': 23
}
const updatedEmp = {...employee, 'age': '25'};
console.log(updatedEmp); // {name: 'Bob', address: 'California', age: '25'}
console.log(employee); // {name: 'Bob', address: 'California', age: 23}
Here we have updated the age
property of the employee object.
Creating Array Literals
You can create arrays in JavaScript using array literal, like this:
const someArray = [1, 2, 3, 4];
As the spread
operator helps us spread the array elements; we can use it to insert the elements from another array into an array while initializing it.
const someArray = [1, 2, 3, 4];
const array = [...someArray, 5, 6, 7];
console.log(array); // [1, 2, 3, 4, 5, 6, 7]
Concatenating Arrays
How we used the spread
operator to combine two objects, we can also concatenate one or more arrays.
const thingsIHate = ['π₯', 'π₯', 'π'];
const thingsILove = ['π', 'π', 'π'];
const myFoodHabit = [...thingsIHate, ...thingsILove];
console.log(myFoodHabit); // ['π₯', 'π₯', 'π', 'π', 'π', 'π']
As the example above shows, we have concatenated two arrays to create a new array. The original arrays remain unchanged.
Expanding the Characters of a String
The spread
operator can help us expand the characters of a string and bundle them together in an array. Here is an example:
const punchLine = 'We love Showwcase';
const extractedChars = [...punchLine];
console.log(extractedChars);
The output,
['W', 'e', ' ', 'l', 'o', 'v', 'e', ' ', 'S', 'h', 'o', 'w', 'w', 'c', 'a', 's', 'e']
This functionality can be handy for expanding a string in-place
to create an array of characters.
let smileys = ['π', ...'ππ', 'π', 'π€£'];
console.log(smileys); // ['π', 'π', 'π', 'π', 'π€£']
The Rest Operator(Parameter)
Let us now move on to learn the Rest
operator, or rather we should call it as Rest Parameter
. The rest parameter is the opposite of the spread operator while using the same syntax, ...
(the three dots).
The rest parameter helps collect the elements together while the spread operator spreads them. The primary usage of the rest parameter comes from collecting the rest of the function arguments together into an array.
function myFunc(x, y, ...rest) {
console.log(rest);
}
myFunc('a', 'b', 'c', 'd', 'e'); // ['c', 'd', 'e']
Please note you can give any name to the rest parameter while using it in the function argument.
Consolidate the Remaining Object using the Rest Operator
When you use destructuring to extract key values from an object, you can consolidate the remaining part of the object using the rest
operator.
In the code snippet below, we destructure the employee
object and extract the value of the address
property. At the same time, we consolidate the remaining object into a new object using the rest
operator.
const employee = {
'name': 'Bob',
'address': 'California',
'age': 23
}
const {address, ...rest} = employee;
console.log(address); // California
console.log(rest); // {name: 'Bob', age: 23}
What's From Here?
That's all. We hope this article was insightful and provided enough details about JavaScript's spread
and rest
operators. As mentioned in the beginning, practice and make your examples too. If you have queries or comments, please post them in the comment section below.
Keep learning!
javascript
es6
arays