Background
In JavaScript, we tend to use rest & spread operators to keep code simple and easy to read. Both use three dots "..." but the use cases are different. In this post, we will see what these operations are and how to use them.
Before we proceed to looking into individual aspects just remember rest is for collecting elements and spread is for spreading elements.
Rest operator
Let's try to see the rest operators 1st. The rest operator is used to collect the remaining elements in an array. The rest syntax works in both function arguments and arrays. Let's look at an example below
As you can see whatever number of arguments you pass to add function is going to capture 1st two in a & b respectively (in this case 1 & 2) and the remaining ones (values - [3, 4]) will be captured in an argument called rest which is an array.
The rest operator is also used for destructuring arrays like below
Spread operator
The Spread operator introduced in ES6 as the name suggests is used to spread the elements.
For eg, in the above code, you can see how "123" was split automatically into 1,2 & 3 by the spread operator.
We can also use this operator to easily create copies of arrays and objects. For eg.,
NOTE: Spread operator helps maintain immutability requirements. This is helpful when you need data that should not mutate (Eg. Redux state).
As I mentioned before rest and spread operators are used commonly in javascript and we will see more usages and examples in upcoming posts.
No comments:
Post a Comment