spread operator in javascript

spread operator is applied to javascript arrays or any value that can be iterated such as a string or an object. It spreads or extracts the elements of the iterable.

spread operator is an addition in ES6. There are many different uses of this operator such as

  • Merging two arrays.
  • Cloning an array with the ability to add new elements to the new array.
  • Cloning an object with the provision to add new entries to the cloned object.
  • Enables to supply an array directly where a series of arguments is expected such as in Math.max function.

All of these applications of spread will be discussed in this article with examples.
Official mozilla  docs for spread operator state

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Syntax
spread operator consists of three periods(...) which are applied before the iterable(array, string or object) that needs to be expanded or spread. Example,

<script>
   let arr = ['google', 'facebook', 'youtube'];
   // extract array with spread operator
   console.log(...arr); // will print google facebook youtube
</script>

From the above output, you can see the spread operator extracts the contents of array. Remember that you cannot assign the extracted contents to another variable. That is, you cannot do something like this

let extract = ...arr;

This will raise Unexpected token ‘…’ error. This is because it would be translated to

let extract = google facebook youtube;

which clearly looks illegal.
There is much more that you can do with spread operator and all of those are discussed below.

Merge arrays with spread
Suppose you want to merge the contents of one array into another. A common approach would be to iterate over the array which you want to merge and push its element into the other array as shown below.

<script>
   let arrayOne = [1, 2, 3];
   let arrayTwo = [4, 5];
   // iterate over the second array
   for(let i = 0; i < arrayTwo.length;i++) {
      // add element to first array
      arrayOne.push(arrayTwo[i]);
   }
   // print first array
   console.log(arrayOne); // prints [1, 2, 3, 4, 5]
</script>

spread operator can be used to accomplish exactly the same task but in a much more easier and shorter way as shown below.

<script>
   let arrayTwo = [4, 5];
   let arrayOne = [1, 2, 3, ...arrayTwo];
   // print first array
   console.log(arrayOne); // prints [1, 2, 3, 4, 5]
</script>

spread operator when placed before an array extracts its contents and spreads them out .
Another flexibility with merging arrays using spread operator is that you can merge an array at the location you want, that is, at the beginning, in the middle or at the end(that we just saw above). Thus,

<script>
   let arrayTwo = [4, 5];
   // merge array in between with spread
   let arrayOne = [1,  ...arrayTwo, 2, 3];
   // print first array
   console.log(arrayOne); // prints [1, 4, 5, 2, 3]
</script>

This would become complex with the looping approach.

Splitting a string into characters
spread operator may be used to extract the characters from a string in the form of an array. This might be useful when you want to iterate over the characters of an array for checking if the string contains a numeric character. Example,

<script>
   let name = 'codippa';
   let chars = ...name;
   console.log(chars); // prints ['c', 'o', 'd, 'i', 'p', 'p', 'a',]
</script>

Cloning an array
A spread operator can be used to create a clone of an array. As we saw above, spread when placed before an array extracts its elements.
These elements when placed between square brackets will create a new array. Note that the new array is not a copy but a fresh array object with the contents of the original array.
It means that if you modify the contents of the new array, the original array remains unchanged. Example,

<script>
   let arr = ['a', 'b', 'c'];
   // create a clone
   let cloned = [...arr];
   // add an element to new array
   clone.push('d');
   // print arrays
   console.log(cloned); // prints ['a', 'b', 'c', 'd']
   console.log(arr); // prints ['a', 'b', 'c']
</script>

Look, the original array remains unchanged. This is different from creating a copy just by assigning an array to a new variable as below.

<script>
   let arr = ['a', 'b', 'c'];
   // create a copy
   let cloned = arr;
</script>

In this method, if you modify the new array, the original array will also be modified.
Cloning an object
Similar to the method of cloning arrays, spread can also be used to create a clone of a javascript object. Though there are different methods to clone an object in javascript but the one with spread is the easiest and shortest.
In order to clone an object place the spread operator before the object and enclose them between curly braces(which is the syntax of creating an object in javascript).
Example,

<script>
   let website = { name: 'codippa', 
                   type:'education'
                 };
   // create object clone
   let cloned = {...website};
   console.log(cloned); // prints { name: 'codippa', type:'education' };
</script>

You can also add additional properties in the new object as shown below.

<script>
   let website = { name: 'codippa', 
                   type:'education'
                 };
   let cloned = { ...website, genre: 'tech' };
   console.log(cloned);  // prints { name: 'codippa', type:'education', genre: 'tech' }
</script>

In this case also, the original object remains unchanged.

Passing array to functions
Math object in javascript contains utility methods for performing mathematical operations such as max method for finding maximum from some numbers.
This method accepts a series of numbers out of which it returns the maximum number. But what if you pass an array to this method as shown below.

<script>
   let numbers = [2, 4, 5, 1, 20];
   // pass array to function
   let max = Math.max(numbers);
   console.log(max);
</script>

This will not print the maximum number but will print NaN which means that you cannot pass an array to Math methods.
But, with spread operator you can pass an array to Math functions as shown below.

<script>
   let numbers = [2,4,5,1,20];
   // pass array with spread
   let max = Math.max(...numbers);
   console.log(max);
</script>

This makes sense since spread operator extracts the elements of an array. Thus when spread is applied to the array, it will be transformed to Math.max(2, 4, 5, 1, 20).
In fact, any function which expects arguments can be called with an array with spread operator as shown in the below example.

<script>
   // add three arguments
   function adder(numOne, numTwo, numThree) {
      return numOne + numTwo + numThree;
   }
   // declare array
   let numbers = [23, 56, 22];
   // pass array with spread operator
   let sum = adder(...numbers);
   console.log(sum); // prints 111
</script>

Without spread, you need to pass three separate numbers to a function.
Hope this article clarified the usage of spread operator introduced as a new feature in ES6. Click the clap if the article was helpful.

0

Leave a Reply

Mark Your Impression

  Subscribe  
Notify of
Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.