iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Spread / Rest

The ... token does two opposite things depending on context: spread (unpacks an iterable) or rest (collects items into one).

Spread — unpack into another structure

JS
// Copy an array (shallow)
const copy = [...arr];

// Concatenate
const all = [...a, ...b, ...c];

// Insert
const middle = [1, 2, ...inserted, 5, 6];

// Spread into function args
Math.max(...[3, 1, 4, 1, 5, 9]);   // 9

// Convert iterable to array
const chars = [..."hello"];        // ["h","e","l","l","o"]
const arr   = [...new Set(nums)];  // unique numbers

Spread into objects (ES2018+)

JS
// Shallow merge — later properties win
const merged = { ...defaults, ...override };

// Immutable update
const updated = { ...user, age: user.age + 1 };

// Pull out a few fields, keep the rest
const { password, ...safeUser } = user;

Rest — collect into one

JS
// Function rest parameter (always last)
function sum(...nums) {
  return nums.reduce((t, n) => t + n, 0);
}
sum(1, 2, 3, 4);   // 10

// Array rest
const [first, ...others] = [1, 2, 3, 4];

// Object rest
const { id, ...payload } = req.body;

Spread vs. rest at a glance

SpreadRest
WhereRight-hand side, function call siteLeft-hand side, parameter list
EffectUnpacks itemsCollects items
PositionAnywhereAlways last
Note: Spread is a shallow copy. Nested objects/arrays still share references with the original — use structuredClone(x) for a deep clone.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Spread / Rest!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Shallow-merge two objects, with override winning.

const merged = { ...defaults, override };

Test yourself

Q1. Copy an array (shallow) with…
Q2. Rest parameters must be…
Q3. Spread on objects is a…

Discussion

Loading…