Skip to main content

What is the spread operator?

The spread operator ... expands an array or object into its individual elements. It’s how you copy, merge, and build new data structures without mutating the originals.
You’ll use the spread operator constantly in React, where you need to create new arrays and objects instead of mutating state.

Array spreading

Copying an array

Python mental model: copy = [...original] is like copy = [*original] or copy = original.copy(). In all cases, this is a shallow copy.

Merging arrays

Adding items without mutation

In React, never use .push() or .pop() on state arrays. Instead, use spread to create new arrays: setItems([...items, newItem]). This tells React that the data changed and it needs to re-render.

Object spreading

Copying an object

Merging objects

Properties from later objects override earlier ones. userPrefs.theme (“dark”) overrides defaults.theme (“light”).

Updating a property without mutation

This is the pattern you’ll use in React state updates:
Spread creates a shallow copy. If your object contains nested objects, the inner objects are still shared references. For deep nested updates, spread each level: { ...user, address: { ...user.address, city: "Seattle" } }.
Python mental model: this is the same behavior as dict.copy() or {**user} — nested dicts/lists are still shared unless you copy those nested levels too.

Practical patterns

Building API request bodies

Removing a property (rest + spread)

This combines destructuring (to grab password) with rest syntax (...safeUser to collect everything else). It’s a clean way to strip sensitive fields.

Conditional properties

The ...(condition && { props }) pattern conditionally includes properties. If the condition is false, false is spread (which adds nothing). You’ll see this when building request bodies with optional fields.
Python mental model: this is similar to {**base, **({"role": "admin"} if is_admin else {})}.

Comparing to Python

JavaScript’s ... is like Python’s * for lists and ** for dicts. Same concept, same patterns.

What’s next?

You can work with arrays and objects. Now let’s learn about JSON — the format your frontend and backend use to exchange data.

JSON basics

Convert between JSON strings and JavaScript objects