JSpread Operator

What is Spread Operator?

The JavaScript ES6 version has brought a whole array of new tools and utilities. One such new feature is the spread operator.

The operator’s shape is three consecutive dots and is written as: ...

It allows an iterable to expand in places where 0+ arguments are expected.

you can use the spread operator on Arrays and objects. you can use them in different cases: Expanding Arrays or objects, Combining or Merging Arrays and Objects, Cloning Arrays and Objects and Using with Math Functions.

Definitions are tough without context. Let’s explore some different use cases:

Expanding Arrays or objects:

Expand arrays or objects with new elements or in other names adding elements or properties to arrays or objects and operations on arrays(push-unshift):

Arrays:

Example1:

let pokemon= ['arbok','kfc','mack'];
//push
pokemon = [...pokemon,'sfdsdfs', 'tyutyu', 'bnmbn' ];
console.log(pokemon) //output: ['arbok','kfc','mack', 'sfdsdfs', 'tyutyu', 'bnmbn']
//unshift
pokemon = ['sfdsdfs', 'tyutyu', 'bnmbn', ...pokemon ];
console.log(pokemon) //output: ['sfdsdfs', 'tyutyu', 'bnmbn', 'arbok','kfc','mack']

Example2:

Objects:

Another Example:

Combining or Merging Arrays and Objects:

Let’s say we have lists from two different sources and we want to combine both these sources and make a single list:

Cloning Arrays and Objects:

Clone array:

Never do the following code with cloning:

why?

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array, so if you will do the following code:

Cloning with Objects:

Using with Math Functions

JavaScript has a Math object which contains several methods to operate with a set of data, i.e. a list of data.

Let us say we want to get the maximum value from the first three numbers of a list:

What if we want to get the maximum of all numbers in a list? What if the list has n number of items? Surely we won't want arr[0], arr[1]... arr[1000].

The spread operator provides a cleaner solution:

The spread operator combines well with Math.min() to find the smallest number in an array:

Accept any number of arguments in a function:

If you don’t know how many arguments you need to accept in an arrow function, you can use the spread operator with the ‘rest’ parameter to make this work:

Some Tricks with Spread:

1- First One

2-Secon Trick:

Sometimes, we may feel the need to convert a String into a list of characters. We can use spread operator for this use-case:

3- Organize Properties

Sometimes properties aren’t in the order we need them to be. Using a couple of tricks we can push properties to the top of the list or move them to the bottom.

To move id to the first position, add id: undefined to the new Object before spreading object.

4-Forth Trick:

5-Fifth Trick:

Shallow Copy & Deep Copy:

Please note spread only goes one level deep when copying an array. So if you're trying to copy a multi-dimensional array, you will have to use other alternatives.

Here’s an interesting thing I learned. A shallow copy means the first level is copied, deeper levels are referenced.

The problem

The spread syntax and the Object.assign() the method can only make shallow copies of objects. This means that the deeply nested values inside the copied object are put there just as a reference to the source object.

Wrong solutions

Online you will find many wrong suggestions:

  1. Using Object.create():

Here the original object is being used as the prototype of copied.

It looks fine, but under the hoods, it’s not:

2. JSON serialization:

This only works if you do not have any inner objects and functions, but just values.

But you will have the following side effects:

You will lose any JavaScript property that has no equivalent type in JSON, like Function or Infinity. Any property that’s assigned to undefined will be ignored by JSON.stringify, causing them to be missed on the cloned object.

Also, some objects are converted to strings, like Date objects for example (also, not taking into account the timezone and defaulting to UTC).

So How we can clone an Object with Right Way?

1-Using Lodash Clone And Clonedeep

Lodash comes with two different functions that allow you to do shallow copies and deep copies. These are clone and clonedeep.

Lodash has this nice feature: you can import single functions separately in your project to reduce a lot the size of the dependency.

Take Look at the following example to understand:

2-Using immutability-helper Library:

Mutate a copy of an object without changing the original source.

Setup via NPM

We can get this library via NPM: npm install immutability-helper --save. To deep copy our object, we could use the update() method available in immutability-helper, passing the object we want to copy as the first argument and the actual data to change as the second one:

Last updated

Was this helpful?