How to Use the Spread Operator in JavaScript
Copying and combining arrays and objects with three dots.
There are times when you need to copy an array, merge two objects or pass the
items of an array into a function as separate arguments. The spread operator
handles all of these with three dots: ....
The spread operator expands an array or object into its individual items or properties.
Copying an Array
Spreading an array into a new array literal creates a copy:
const original = [1, 2, 3]const copy = [...original]copy.push(4)console.log(original) // [1, 2, 3]console.log(copy) // [1, 2, 3, 4]
Since copy is a new array, changing it doesn't touch original.
Combining Arrays
You can spread as many arrays as you want into one, and add items anywhere in between:
const frontEnd = ["HTML", "CSS"]const backEnd = ["Node", "Postgres"]const stack = [...frontEnd, "JavaScript", ...backEnd]// ["HTML", "CSS", "JavaScript", "Node", "Postgres"]
Spreading into Function Arguments
Some functions take separate arguments instead of an array, like Math.max.
Spread turns the array into those arguments:
const scores = [72, 95, 88]Math.max(scores) // NaNMath.max(...scores) // 95
Copying and Merging Objects
Spread works on objects too. This is the easiest way to copy an object and change a few properties at the same time:
const user = { name: "Jim", role: "Sales", location: "Scranton" }const promoted = { ...user, role: "Manager" }// { name: "Jim", role: "Manager", location: "Scranton" }
Properties that come later win, so role: "Manager" replaces the one from
user. The same rule applies when merging two objects:
const defaults = { theme: "light", fontSize: 16 }const settings = { fontSize: 20 }const config = { ...defaults, ...settings }// { theme: "light", fontSize: 20 }
You'll see this pattern a lot in React and Redux, where you never change state directly and always create a new object instead.
Spread Makes Shallow Copies
Spread only copies one level deep. If your object has another object inside of it, both copies still point to the same inner object:
const original = { name: "Pam", address: { city: "Scranton" } }const copy = { ...original }copy.address.city = "New York"console.log(original.address.city) // "New York"
Note: To copy nested data you need to spread each level you change, like
{ ...original, address: { ...original.address, city: "New York" } }.
Spreading Strings
Strings can be spread too, which splits them into an array of characters:
;[..."hello"] // ["h", "e", "l", "l", "o"]
Spread can replace most of the places where you would have used concat or
Object.assign.
Have some feedback on this post? .