JavaScript Spread Operator (…) Guide: Copy, Merge, and Spread vs. Rest Explained

  • Home
  • JavaScript Spread Operator (…) Guide: Copy, Merge, and Spread vs. Rest Explained

JavaScript Spread Operator (...): Copying and Merging Data Cleanly and Safely

The Spread Operator (...) expands elements of an iterable (such as an Array or String) or enumerable properties of an Object directly where they are needed. Instead of mutating original data structures or writing verbose loops, ... lets you copy and merge data concisely, improving readability and preventing unintended side effects.

1. Copying Data (Shallow Copy)

Copying an Array

Assigning const b = a points both variables to the same memory reference. Using ... creates a new top-level array:

JavaScript

const originalTags = ['js', 'es6', 'frontend'];
const clonedTags = [...originalTags];

clonedTags.push('dcsofttech');

console.log(originalTags); // ['js', 'es6', 'frontend']
console.log(clonedTags);   // ['js', 'es6', 'frontend', 'dcsofttech']

Copying an Object

Similarly, you can clone an object while overriding or adding properties in a single expression:

JavaScript

const user = {
  id: 101,
  name: 'Alex',
  role: 'editor'
};

const updatedUser = {
  ...user,
  role: 'admin',
  active: true
};

console.log(user);        // { id: 101, name: 'Alex', role: 'editor' }
console.log(updatedUser); // { id: 101, name: 'Alex', role: 'admin', active: true }

Key Note: The spread operator performs a shallow copy. If an array or object contains nested objects or arrays, those nested references are still shared. When you need a full deep clone, use structuredClone() or clone nested levels explicitly.

2. Merging Data (Arrays & Objects)

Merging Arrays and Inserting Elements Anywhere

You can combine multiple arrays and insert individual items in any order:

JavaScript

const frontendStack = ['HTML', 'CSS', 'JavaScript'];
const backendStack = ['Node.js', 'Laravel'];

const fullStack = ['Git', ...frontendStack, ...backendStack, 'Docker'];
// ['Git', 'HTML', 'CSS', 'JavaScript', 'Node.js', 'Laravel', 'Docker']

Merging Objects and Override Order

When merging multiple objects with ..., later properties overwrite earlier ones with the same key:

JavaScript

const defaultConfig = {
  theme: 'light',
  pageSize: 10,
  showSidebar: true
};

const userConfig = {
  theme: 'dark',
  pageSize: 20
};

const finalConfig = {
  ...defaultConfig,
  ...userConfig
};

console.log(finalConfig);
// { theme: 'dark', pageSize: 20, showSidebar: true }

Reversing the order to { ...userConfig, ...defaultConfig } causes defaultConfig to overwrite userConfig. Property order directly determines the final result.

3. Passing Function Arguments

The spread operator unpacks array elements into individual arguments when calling a function:

JavaScript

const scores = [12, 45, 8, 91, 34];

const maxScore = Math.max(...scores); // 91
const minScore = Math.min(...scores); // 8

Prior to ES6, achieving this required Math.max.apply(null, scores), which was harder to read and maintain.

4. Spread (...) vs. Rest (...) at a Glance

Although both use three dots (...), their roles are exact opposites depending on context:

Aspect Spread Operator (…) Rest Parameter / Syntax (…)
Role Expands elements or properties into individual items Collects remaining arguments or items into an array/object
Common Context Function calls, array literals [...a], object literals {...obj} Function parameters (...args) or destructuring assignments
Primary Use Copying, merging, passing arguments Handling variadic arguments, extracting remaining properties

Example of Rest syntax in a function parameter:

JavaScript

function sumAll(...numbers) {
  return numbers.reduce((total, current) => total + current, 0);
}

console.log(sumAll(10, 20, 30)); // 60

5. Practical Tips for Production Code

  • Watch out for non-iterables in array spreads: Spreading null or undefined inside an object literal ({ ...maybeNull }) safely does nothing, whereas spreading a non-iterable value inside an array literal ([...maybeNull]) or function call throws a TypeError.

  • Avoid repeated cloning inside large loops: Creating new copies on every iteration of a large dataset increases memory allocation and garbage collection overhead. Mutate a local accumulator or build the structure once when performance matters.

  • Quick deduplication for primitive arrays: Pair Set with ... to remove duplicate primitive values in one line:

JavaScript

const rawIds = [1, 2, 2, 3, 4, 4, 5];
const uniqueIds = [...new Set(rawIds)]; // [1, 2, 3, 4, 5]

Mastering the JavaScript spread operator (...) gives you a clean, predictable way to handle immutable updates, configuration overrides, and data transformations across modern codebases.

Categories:

Leave Comment

December 2026
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
28293031