Posted

2 minutes read

The ES6 Spread Operator can be used for arrays and objects.

Array Spread Operator

We define iterables as: strings, arrays, sets.
Basically if you can loop over, then your property can be an iterable.

The three dots act upon the number or string and it spread each item (character or number).

Array Spread Operator for Strings


const myString = 'TESTING';
const characters = [ ...myString ];

//[ 'T', 'E', 'S', 'T', 'I', 'N', 'G' ]

Array Spread Operator for Numbers


const middle1 = [3, 4];
const middle2 = [7, 8];

const result = [1, 2, ...middle1, 5, 6, ...middle2, 9, 10];

// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Spread Operator for String to Array


const welcomeMessage = 'Hello World!'

const chars = [...welcomeMessage]

// [ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!' ]

Applying a method to an array using Spread Operator


const numbers = [1, 2, 3, 4, 5, 6]

const minElement = Math.min(...numbers)

const maxElement = Math.max(...numbers)

// 1
// 6

Object Spread Operator

The Spread Operator just iterates through the array and lists each element in the receiver object.


const people = [{ lastname: 'John' }, { lastname: 'Andrew' }]

const people2 = { ...people }

// { '0': { lastname: 'John' }, '1': { lastname: 'Andrew' } }

Let’s assume you have an object, and you want to create a new object with different properties.

You can specify only the properties you want and use the Object Spread Operator for the rest.


const dev1 = {
  name: 'John Doe',
  occupation: 'Software developer',
  age: 20,
}

const dev2 = {
  ...dev1,
  name: 'Jane Doe',
  age: 30,
}

// { name: 'Jane Doe', occupation: 'Software developer', age: 30 }

Basically you can think at this like, the spread operator extracts all individual properties one by one and transfers them to the new object.
So, we won’t have any duplicate properties in the newly created object, we just overwrite the original values of those properties that are coming from the original object.

And here is how the spread operator works in an arrays versus objects.