JS ES6 spread operator with examples

In this post, we are going to understand the new JS ES6 spread operator with examples. We often use for, foreach, or for-in loop to iterate over an array, set, string and object by element by element and it is time-consuming. But we can do it with a lesser and cleaner code by using the spread operator.

What is spread operator in ES6


The spread operator is a new operator introduced in ES6 Standard of JavaScript, It is represented by three dots(…) same as the Rest parameter, but it works opposite of the Rest parameter It takes an iterate object(Array, Set, Map, String) and Object and spread their element.

Syntax

//syntax passing as function agrument

funname(…iterableObject)


//Syntax For array literals or strings:

[…iterableObject, 'xyz', 's'];


//Syntax object literals (new in ES 2018)
let copy_object= { ...object };


How to Spread operator with array


In these below multiple examples, we are going to understand how to use spread operator with an array in javascript like joining arrays, adding elements at any index by using spread operator, use of spread operator as function argument instead of apply.

1.1 Replace apply() with spread operator


In Earlier ES6, We used to pass the Array element as an argument to function with Apply() method, We can replace it with the Spread operator in ES6 with less and cleaner code.

Before the ES6 spread operator, array elements were used to spread in a function by using apply() method.et us consider below example

function without_spreadopertaor(x, y, z) { 
  
  console.log(`array element = ${x},${y},${z}`)
  
}
let array = [0, 1, 2];

without_spreadopertaor.apply(null, array);

Output

array elements = 0,1,2

1.2.Replace Apply() arguments with Spread operator


Here, we are using the Spread Operator to pass an array as an argument with less and cleaner code. Spread operator make us perform some operation on Array easily and less code

function spreadopertaor(x, y, z) { 
  
  console.log(`array elements = ${x},${y},${z}`)
  
}
let array = [0, 1, 2];

without_spreadopertaor( ...array);

Output

array elements = 0,1,2

1.3. Join two array with Spread operator


In this example, we are using a spread operator to join multiple arrays into a single array.

let arraylang = ['JS', 'C#', 'JQuery'];
let array = [1, 7, 5]; 

arraylang = [...arraylang, ...array]; 

Output

[ 'JS', 'C#', 'JQuery', 1, 7, 5 ]

1.4.Insert array at start of existing Array using Spread Operator


Earlier we used to have Array.prototype.unshift() to add a number of elements at beginning of the existing array.

let lastname = ['Jack', 'Rack','Mack'];
let name = ['Tap', 'map', 'Gap'];

lastname = [...name, ...lastname];

Output

[ 'Tap', 'map', 'Gap', 'Jack', 'Rack', 'Mack' ]

1.5 Spread operator to Push elements in Array


We can add elements to an array using spread operator as doing in the below example

let lastname = ['Jack', 'Rack','Mack'];
let name = ['Tap', 'map', 'Gap'];
name.push(...lastname)
console.log(name)

Output

[ 'Tap', 'map', 'Gap', 'Jack', 'Rack', 'Mack' ]

2. Spread operator with String


In programming often we need to convert a string into characters using Spread Operator. It can be achieved easily.

let str = "Example";
let chars = [...str];
console.log(chars);

Output

[
  'E', 'x', 'a',
  'm', 'p', 'l',
  'e'
]

3. Spread Operator with Object literal


It makes an object copy its own property to another object. It is introduced in ES2018. Spread Operator makes us use shorter syntax to do a shallow copy. than Object.assign().

let object_name = { name: 'jack', age: 42 };
let object_name2 = { lastname: 'Rick', address: 'US' };

let copy_object = { ...object_name };


let mergeobject = { ...object_name, ...object_name2 };
console.log(mergeobject)

Output

{ name: 'jack', age: 42, lastname: 'Rick', address: 'US' }

Important Note: Objects are not iterable themselves, But Objects can be made to behave as iterable when we use them with Array, Map(), reduce(), and assign().

4. Math Function with Spread Operator


We can easily perform the Math operation using Spread Operator. Let us take an example where we have to find the Min, Max from an array. We have to loop through the array then we will get the output, But by using Spread Operator it can be achieved easily.

Here is the Example

const numbers = [1, 2, 3,20,21,8,9,11,13,89,60];

console.log(`Max number = ${Math.max(...numbers)}`);
console.log(`min number = ${Math.min(...numbers)}`);

Output

Max number = 89
min number = 1