JavaScript - Spread & Rest Operators

Overview

Estimated time: 20–30 minutes

Spread expands iterable elements or object properties; rest collects remaining items into an array or object.

Learning Objectives

  • Clone/merge arrays and objects with spread.
  • Use rest parameters in functions and destructuring.

Prerequisites

Examples

// Spread arrays
const a = [1,2];
const b = [...a, 3]; // [1,2,3]

// Spread objects (shallow)
const u = { id: 1, name: 'Ada' };
const v = { ...u, name: 'Ada Lovelace' };

// Rest parameter
function sum(...nums){ return nums.reduce((a,b)=>a+b,0); }
sum(1,2,3); // 6

// Rest in destructuring
const [head, ...tail] = [1,2,3]; // head=1, tail=[2,3]

Common Pitfalls

  • Spread/rest are shallow; nested objects/arrays remain shared references.