The JavaScript Spread Operator

By

Published · Updated

Tagged: JavaScript

Learn how JavaScript spread syntax expands iterables into arrays or function arguments and copies enumerable properties into object literals.

The spread syntax ... expands values in three places:

Although people call it the spread operator, the specification defines it as syntax. See the MDN spread syntax reference for the complete rules.

Let’s start with an array example. Given

const a = [1, 2, 3]

you can create a new array using

const b = [...a, 4, 5, 6]

You can also create a shallow copy of an array:

const c = [...a]

Object spread creates a shallow copy of an object’s own enumerable properties:

const newObj = { ...oldObj }

It does not copy the prototype or non-enumerable properties. Nested objects are still shared with the original.

Strings are iterable, so spreading a string creates an array of Unicode code points:

const hey = 'hey'
const arrayized = [...hey] // ['h', 'e', 'y']

You can also spread an iterable into a function call:

const add = (a, b) => a + b
const numbers = [1, 2]

add(...numbers) //3

Spread and rest are different

Rest syntax also uses ..., but it does the opposite. Spread expands values, while rest collects them.

The rest element is useful with array destructuring:

const numbers = [1, 2, 3, 4, 5]
const [first, second, ...others] = numbers

Spread passes the collected values as separate arguments:

const numbers = [1, 2, 3, 4, 5]
const sum = (a, b, c, d, e) => a + b + c + d + e
const result = sum(...numbers)

ES2018 introduced rest and spread properties for objects.

Rest properties:

const { first, second, ...others } = {
  first: 1,
  second: 2,
  third: 3,
  fourth: 4,
  fifth: 5
}

first // 1
second // 2
others // { third: 3, fourth: 4, fifth: 5 }

Spread properties create a new object from existing properties:

const items = { first, second, ...others }
items //{ first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }

You can merge simple objects too. Later properties overwrite earlier properties with the same name:

const object1 = {
  name: 'Flavio'
}

const object2 = {
  age: 35
}

const object3 = { ...object1, ...object2 }

object3 is { name: 'Flavio', age: 35 }.

Order matters

Properties are copied left to right, so the last one wins. This gives you a handy pattern for default options:

const defaults = { theme: 'light', lang: 'en' }

const settings = { ...defaults, theme: 'dark' }
// { theme: 'dark', lang: 'en' }

Flip the order and the defaults overwrite your value:

const settings = { theme: 'dark', ...defaults }
// { theme: 'light', lang: 'en' }

Adding a property only if a condition is true

Spreading false, null or undefined into an object literal adds nothing, and doesn’t throw. You can use this to add a property conditionally:

const isAdmin = false

const user = {
  name: 'Flavio',
  ...(isAdmin && { role: 'admin' })
}
// { name: 'Flavio' }

This only works in object literals. In an array or a function call, spreading null or undefined throws:

[...null] // TypeError: null is not iterable

Spread copies are shallow

This is the pitfall that bites most people. Spread copies one level deep. Nested objects and arrays are shared between the copy and the original:

const user = { name: 'Flavio', address: { city: 'Rome' } }
const copy = { ...user }

copy.address.city = 'Bologna'
user.address.city // 'Bologna'

Changing copy.name would not affect user, but address is the same object in both. If you need a full copy, use structuredClone():

const copy = structuredClone(user)

I cover the options in how to deep clone a JavaScript object.

Turning other iterables into arrays

Anything iterable can be spread into an array. This is a quick way to get array methods on a Set, a Map, a NodeList or the arguments object:

const unique = [...new Set([1, 2, 2, 3])] // [1, 2, 3]

const entries = [...new Map([['a', 1]])] // [['a', 1]]

const links = [...document.querySelectorAll('a')]
links.map((link) => link.href)

Plain objects are not iterable, so this fails:

const obj = { a: 1 }
const array = [...obj] // TypeError: obj is not iterable

Use Object.keys(), Object.values() or Object.entries() instead.

Strings are split into code points, not into what you see as characters. An emoji with a skin tone modifier is one symbol on screen but two code points:

[...'👍🏽'].length // 2

Math.max with an array

Math.max() takes separate arguments, not an array. Spread fixes that:

const numbers = [3, 7, 1]
Math.max(...numbers) // 7

Every spread value becomes a function argument, and JavaScript engines have a limit on how many arguments a call can take. With a very large array the call fails. In my test with Node 22, Math.max(...array) on 200,000 numbers threw RangeError: Maximum call stack size exceeded. For big arrays, use a loop or reduce():

const max = numbers.reduce((a, b) => Math.max(a, b))

Spread vs Object.assign()

Object.assign(target, source) also copies properties, but there are two differences:

const target = {
  set x(value) {
    console.log('setter ran', value)
  }
}

Object.assign(target, { x: 1 }) // logs "setter ran 1"
const result = { ...target, x: 2 } // logs nothing

In everyday code, where you just want a new object with some changes, spread is the simpler choice.

Want me to talk about your product? You can sponsor this site.

Related posts about js: