Javascript

How to Use the Spread Operator (…) in JavaScript

ES6 Spread Operator in detail, how it works, the good, the bad, the ugly

Copy arrays or objects

Look at the following script, can you tell what’s the output?

const listA = [1, 2, 3]
const listB = listA
listB.push(4)
console.log('listA:', listA)
console.log('listB:', listB)
"listA:" [1, 2, 3, 4]
"listB:" [1, 2, 3, 4]
const listB = listA
const listC = [1, 2, 3]
const listD = [...listC]
listD.push(4)
console.log('listC:', listC)
console.log('listD:', listD)
"listC:" [1, 2, 3]
"listD:" [1, 2, 3, 4]
const article = {
title: 'How to Use the Spread Operator (...) in JavaScript',
claps: 1000000,
author: {
name: 'Juan',
publication: 'LiveCodeStream'
}
}

const articleCopy = { ...article }


articleCopy.title = 'Strange behaviours with spread operator and deep copy';
articleCopy.author.name = 'JC';

console.log('Original title:', article.title);
console.log('Original author:', article.author.name)

console.log('Copy title:', articleCopy.title)
console.log('Copy author:', articleCopy.author.name)
Original title:	How to Use the Spread Operator (...) in JavaScript
Original author: JC
Copy title: Strange behaviours with spread operator and deep copy
Copy author: JC

Merging arrays or objects

The spread operator is very useful to copy objects, but we can also use it to merge multiple objects or lists into a single object.

const list1 = [1, 2, 3]
const list2 = [4, 5]

const mergedList = [...list1, ...list2]

console.log('Merged List: ', mergedList)
const obj1 = {a: 1, b: 2}
const obj2 = {c: 3}

const mergedObj = {...obj1, ...obj2}

console.log('Merged Object: ', mergedObj)
Merged List: 	[1,2,3,4,5]	
Merged Object: {"a":1,"b":2,"c":3}
const weird1 = {...obj1, ...list2}
console.log('Merged list as object', weird1)
Merged list as object	{"0":4,"1":5,"a":1,"b":2}
const weird2 = [...obj1, ...list1]
console.log('Merged list as object', weird2)
object is not iterable (cannot read property Symbol(Symbol.iterator))

Passing arguments

Have you ever tried to find the maximum (or minimum) value on an array? Your first answer to this question is probably to use the Math.max function, however, it won't work, we need to do something else. Why?

console.log('Math.max(1, 2, 3)', Math.max(1, 2, 3))
console.log('Math.max([1, 2, 3])', Math.max([1, 2, 3]))
console.log('Math.max(...[1, 2, 3])', Math.max(...[1, 2, 3]))
Math.max(1, 2, 3)	3	
Math.max([1, 2, 3]) null
Math.max(...[1, 2, 3]) 3
function test(param1, ...args) {
console.log(' -> param1', param1)
console.log(' -> args', args)
}

console.log('test(1):')
test(1)

console.log('test(1, "a", "b", "c"):')
test(1, 'a', 'b', 'c')
test(1):	
-> param1 1
-> args []
test(1, "a", "b", "c"):
-> param1 1
-> args ["a","b","c"]

Destructing arrays or objects

We saw how to copy and merge objects, but…. can we “unmerge” objects? It’s called destructing… and yes! let’s take a look:

console.log('first', first)
console.log('second', second)
console.log('rest', rest)
first	1	
second 2
rest [3,4,5]
const article = {
title: 'Cool article',
claps: 10000000,
author: {
name: 'Juan'
}
}

const { title, claps, author: { name }} = article

console.log('title', title)
console.log('claps', claps)
console.log('author name', name)
title	Cool article	
claps 10000000
author name Juan

NodeList to Array

Simply as it sounds we can do something like:

[...document.querySelectorAll('div')]

Convert string to characters

A string is an iterable, and we can use them to expand them as a list of characters as follows:

const name = 'Juan'
const chars = [...name];

Remove duplicates

Can we use spread operators to get only unique values? Yes, but not directly… we would need to make use of something else in conjunction with the spread operator, Sets.

const list = [1, 3, 1, 3, 3, 2]
const uniqueList = [...new Set(list)]
[1, 3, 2]

Conclusion

The spread operator (…) is very useful for working with arrays and objects in Javascript. You will see them a lot when working with frameworks such as React, and when developing reducers. It’s definitely an important feature to learn and master if you work with Javascript.

I’m an entrepreneur, developer, author, speaker, and doer of things. I write about JavaScript, Python, AI, and programming in general.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store