The JavaScript Spread Operator
By Flavio Copes
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:
- an iterable into a function’s arguments
- an iterable into an array literal
- an object’s own enumerable properties into an object literal
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 }Related posts about js: