1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Spread Operator Explained: Spread vs Rest, Copies and Gotchas, Tested

The JavaScript spread operator, three dots before a value, expands arrays, strings and objects into individual items. Learn how it copies and merges data, how it differs from rest parameters, and where it breaks, with output we ran on Node 24.

9 min read
JavaScript spread operator explained: spread vs rest, copies and gotchas

Key takeaways

  • The JavaScript spread operator (...) expands an iterable or object into separate values; rest does the opposite and collects values.
  • Spread makes shallow copies: changing a nested object in the copy also changed the original in our test.
  • On Node 24, Math.max(...arr) worked with 100,000 items but threw RangeError at 200,000.
  • Spreading the accumulator inside reduce took 51.7 ms for 5,000 items, against 0.84 ms for a simple loop.

Three dots have become one of the most common sights in modern JavaScript. You see them in React state updates, API helpers, config merging and function signatures. The JavaScript spread operator is short and expressive, but it hides a few traps: copies that are not really copies, a hard limit on function arguments and a hidden quadratic cost.

We ran every snippet below on Node.js v24.22.1 and copied the output. Browsers follow the same language rules, though exact limits such as the maximum argument count can differ by engine. If you are new to the syntax family, our JavaScript destructuring guide covers the closely related pattern syntax, and our JavaScript tutorial for beginners covers the basics.

What is the spread operator?

Spread syntax, written ...value, takes something that holds many items and expands it in place. It works in three positions:

  • Array literals: [...a, ...b] builds a new array from other iterables.
  • Function calls: fn(...args) passes array items as separate arguments.
  • Object literals: {...obj} copies an object’s own enumerable properties.

Strictly speaking, it is syntax rather than an operator, because it cannot be used on its own like +. Everyone still calls it the spread operator, and so will we.

Spreading arrays

Merging and copying arrays is the most common use:

const a = [1, 2], b = [3, 4];
console.log([...a, ...b, 5]);          // [ 1, 2, 3, 4, 5 ]

const copy = [...a];
copy.push(99);
console.log(a, copy);                  // [ 1, 2 ] [ 1, 2, 99 ]

console.log(Math.max(...[4, 9, 2]));   // 9
console.log(Math.max(...[]));          // -Infinity

The copy is a new array, so pushing to it leaves a alone. Spreading into a function call is the modern replacement for Math.max.apply(null, arr). Note the empty case: Math.max() with no arguments returns -Infinity, which can slip into reports unnoticed. For other ways to transform arrays, see our JavaScript array methods guide.

Shallow copies: the most common bug

Spread copies one level deep. Nested objects are shared by reference between the original and the copy:

const nested = [{ n: 1 }];
const sh = [...nested];
sh[0].n = 42;
console.log(nested[0].n);       // 42  (original changed!)

const orig = [{ n: 1 }];
const d2 = structuredClone(orig);
d2[0].n = 7;
console.log(orig[0].n);         // 1   (original safe)

This is the root of many “state changed by itself” bugs in front-end code. When you need a full independent copy of plain data, use structuredClone, which is built into Node and modern browsers. When you update nested state, spread at every level you change, for example {...user, address: {...user.address, city: "Pune"}}.

Strings, Sets and Maps

Array spread works on anything iterable, not just arrays:

console.log([..."héllo"]);                      // [ 'h', 'é', 'l', 'l', 'o' ]
console.log([..."👍🏽ok"].length, "👍🏽ok".split("").length);   // 4 6
console.log([...new Set([3, 1, 3, 2, 1])]);    // [ 3, 1, 2 ]
console.log([...new Map([["a", 1], ["b", 2]])]); // [ [ 'a', 1 ], [ 'b', 2 ] ]

The emoji line is worth a second look. Spreading a string splits it by Unicode code points, while split("") splits by UTF-16 code units, so the same string gave 4 items one way and 6 the other. Spread is the safer choice for counting characters, though a skin-tone emoji is still two code points. Spreading a Set is the shortest way to remove duplicates, and spreading a Map gives its entries. Our Map vs Object guide explains when to choose each.

Spreading objects

Object spread copies own enumerable properties into a new object. When keys collide, the one written later wins:

const base = { theme: "light", lang: "en" };
console.log({ ...base, lang: "fr" });   // { theme: 'light', lang: 'fr' }
console.log({ lang: "fr", ...base });   // { lang: 'en', theme: 'light' }

console.log({ ...null, ...undefined, x: 1 });   // { x: 1 }

class P { constructor() { this.own = 1 } get g() { return 2 } }
P.prototype.proto = 3;
console.log({ ...new P() });            // { own: 1 }

Order matters: put defaults first and overrides last. Spreading null or undefined into an object is silently ignored, which makes optional config easy. But only own properties are copied, so getters and prototype properties from a class instance disappear, and the result is a plain object, not a P. Never use object spread to clone class instances.

Spread vs rest parameters

The same three dots also mean rest, which collects values instead of expanding them. The position tells you which one you are looking at:

function sum(...nums) {                 // rest: collects arguments
  return nums.reduce((s, n) => s + n, 0);
}
console.log(sum(1, 2, 3), sum());       // 6 0

const [first, ...others] = [10, 20, 30];
console.log(first, others);             // 10 [ 20, 30 ]

const { password, ...safe } = { id: 7, name: "Demo", password: "x" };
console.log(safe);                      // { id: 7, name: 'Demo' }
Question Spread Rest
What it does Expands one value into many Collects many values into one
Where it appears Calls, array and object literals Function parameters, destructuring
How many allowed Any number One, and it must be last
Result type Separate values or a new literal A real array or a plain object

Rest parameters produce a true array, so Array.isArray returned true in our test, while the old arguments object returned false. Also, rest parameters are not counted in a function’s length: ((a, b, ...c) => 0).length printed 2. The object-rest pattern above is a tidy way to strip secrets such as a password before logging or sending data.

The argument limit nobody mentions

Spreading into a function call passes every item as a separate argument, and engines limit how many arguments one call can have. We tested Math.max(...arr) with growing arrays:

Array length Result on Node 24.22.1
100,000 Worked
200,000 RangeError: Maximum call stack size exceeded
1,000,000 RangeError
10,000,000 RangeError

A reduce loop handled 10 million items without trouble. If an array can be large, such as rows from a database or a CSV upload, avoid spreading it into a call. The same applies to arr.push(...other): pushing a 200,000-item spread also threw RangeError in our test.

A performance trap: spread inside reduce

A popular one-liner builds a lookup object by spreading the accumulator on every step. It looks clean, but each step copies everything built so far:

// Copies the whole object on every iteration
items.reduce((acc, it) => ({ ...acc, [it.id]: it }), {});

// Mutates one object in place
const o = {};
for (const it of items) o[it.id] = it;

With 5,000 items, the spread version took 51.7 ms and the loop took 0.84 ms in our run, around 60 times slower. The gap grows quadratically with size. Immutability is valuable for shared state, but inside a function that owns its accumulator, plain mutation is safe and fast. Object.fromEntries(items.map(it => [it.id, it])) is a readable alternative; it took 1.78 ms for the same 5,000 items in our run.

Errors you will see

  • TypeError: null is not iterable: array spread on null or undefined. Use [...(list ?? [])].
  • TypeError: ... is not iterable: spreading a plain object into an array. Use Object.values(obj) or Object.entries(obj) first.
  • RangeError: Maximum call stack size exceeded: too many items spread into a function call.
  • Silent shared state: not an error at all, which is why the shallow copy bug survives code review. Test that edits to a copy leave the original unchanged.

JavaScript spread operator cheat sheet

Task Code
Merge arrays [...a, ...b]
Copy an array (shallow) [...a]
Remove duplicates [...new Set(a)]
Merge objects, last wins {...defaults, ...overrides}
Remove a key const {key, ...rest} = obj
Deep copy plain data structuredClone(obj)
Variable arguments function f(...args) {}

Final thoughts

The JavaScript spread operator makes code shorter and intent clearer, as long as you remember what it does under the hood. It copies one level only, it passes every item as a separate argument, and it copies again each time you use it in a loop. Keep those three facts in mind, reach for structuredClone and plain loops when they fit, and the three dots will serve you well. Our JavaScript closures guide is a good next read.

Frequently asked questions

What is the difference between spread and rest in JavaScript?

Both use three dots. Spread expands an array, string or object into separate values. Rest collects separate values into an array or object, in function parameters or destructuring.

Does the spread operator make a deep copy?

No. It makes a shallow copy, so nested objects and arrays are still shared with the original. Use structuredClone for a deep copy of plain data.

Can I use the spread operator on objects?

Yes. Object spread copies own enumerable properties into a new plain object, and later keys override earlier ones. It does not copy prototype properties or class identity.

Why does Math.max with a spread array throw RangeError?

Each item becomes a separate function argument and engines cap the number of arguments. In our Node 24 test it failed at 200,000 items; use a loop or reduce for large arrays.

Is the spread operator slow?

A single spread is fast. It becomes slow when repeated in a loop, such as spreading the accumulator inside reduce, because each step copies everything built so far.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →