The **spread operator** `...` expands iterables. In **arrays**, it copies/merges. In **function calls**, it spreads array elements as arguments. In **objects** (ES2018), it shallow-copies and merges objects. It's non-mutating — always creates a new array/object. Perfect for immutable update patterns.
1Understanding Spread Operator (...)
The spread operator ... expands iterables. In arrays, it copies/merges. In function calls, it spreads array elements as arguments. In objects (ES2018), it shallow-copies and merges objects. It's non-mutating — always creates a new array/object. Perfect for immutable update patterns.
Object spread always creates a shallow copy. Nested objects are still references. Use structuredClone() for deep copies.
// Array operations
const a = [1, 2, 3];
const b = [4, 5, 6];
const merged = [...a, ...b]; // [1,2,3,4,5,6]
const copy = [...a]; // shallow copy
const prepend = [0, ...a]; // [0,1,2,3]
console.log(Math.max(...a)); // 32Practical Example
Here is a real-world application of Spread Operator (...) showing how it is used in production JavaScript code.
// Object spread (immutable updates)
const user = { name: 'Alice', age: 30, role: 'user' };
// Shallow copy
const copy = { ...user };
// Override specific field
const promoted = { ...user, role: 'admin' };
console.log(promoted); // { name:'Alice', age:30, role:'admin' }3Best Practices
Follow these guidelines when working with Spread Operator (...):
1. Use spread for array/object copies and merges
2. Put overriding properties AFTER the spread
3. Know it's a shallow copy for objects and arrays
Tip: Object spread always creates a shallow copy. Nested objects are still references. Use structuredClone() for deep copies.
// Array operations
const a = [1, 2, 3];
const b = [4, 5, 6];
const merged = [...a, ...b]; // [1,2,3,4,5,6]
const copy = [...a]; // shallow copy
const prepend = [0, ...a]; // [0,1,2,3]
console.log(Math.max(...a)); // 3