Applications of JavaScript Spread and Rest Operators

Level up JavaScript skills with ES6/ES2015

To create a copy of Array


image.png

We can create the same copy of the array object with the spread operator with the syntax [...(ARRAY_VARIABLE)] This is the output of the above code

image.png

Both oddArray and copyOfOddArray variables holding the same array of values [1, 3, 5, 7, 9] according to the first two console.log() statements. But how we know those two variables are the same or two different arrays of objects? The answer for this is a third output boolean false. That means they are not the same array of objects. Thripple equals sign === will compare the memory locations of those two array variables and gives the answer as they are two different objects located in different addresses.

BONUS TIP:

You can clone (copy) array in another way (Old JavaScript Way) like below as well.

image.png

OUTPUT:

image.png

To merge (Concat) two arrays into one


image.png

You can use the spread operator to join two arrays into one like the above example. That gives the following output.

image.png

As you can see in the output, individual arrays are spread out and joined into a single array, a new modified array of elements as a combination of those two arrays.

To clone the object


image.png

We can create a clone of an existing object using a spread operator with the syntax {...(OBJECT_VAR)}. This is the output of the above code.

image.png

Both doctor and copyOfDoctor variables holding the same object values. The first two console.log() statements prove that. The third logging output proves those two objects refer to two different memory locations.

BONUS TIP:

You can clone an object in another way (Old JavaScript Way)

image.png

OUTPUT:

image.png

To merge two objects into a single object


image.png

You can use the spread operator to merge two objects into one like the above example. That gives the following output.

image.png

As you can see in the output, both objects are spread out and merged, and constructed a new object with all the attributes of both objects.

Dynamic function arguments as rest operator (...)


image.png

You can use the rest operator with the syntax ...[ARRAY_VAR] to accept entire array elements into a function argument as above example. This gives output as follows.

image.png

BONUS TIP:

You can this in another way with the apply() function (Old JavaScrpt way)

image.png

This give the same output as follows

image.png

Some of the functions in the Javascript Math package support this rest operator for dynamic arguments as an array of values. Following are a few examples. But there are many. Feel free to check out other methods by yourself. Remember, learning makes you perfect and you are the teacher of yourself.

image.png

OUTPUT:

image.png

Thank you so much for reading this post up to this far. Happy learning. Keep going... Cheers!!!

No Comments Yet