CodingNic

Arrays, Objects & Iteration

Destructuring, Spread, and Rest

Arrays, Objects & Iteration 20 min read

Destructuring, Spread, and Rest

Objectives

By the end of this chapter, you should be able to:

  • Destructure values out of arrays and objects into variables
  • Provide default values and rename variables during destructuring
  • Copy and merge arrays and objects with the spread operator
  • Collect leftover items with rest syntax

💡 Why this matters: Once you’re working with real arrays and objects, you constantly need to pull specific values out of them or combine several into one. Destructuring, spread, and rest do that in a single readable line instead of several manual steps.

Array Destructuring

Destructuring pulls values out of an array (or object) into their own variables, matching by position for arrays.

javascript
const point = [10, 20];
const [x, y] = point;
console.log(x, y);
// 10 20

You can skip items you don’t need by leaving a gap.

javascript
const colors = ["red", "green", "blue"];
const [, second] = colors;
console.log(second);
// green

If the array is shorter than the pattern, missing positions are undefined, unless you give them a default value.

javascript
const settings = ["dark"];
const [theme, fontSize = 16] = settings;
console.log(theme, fontSize);
// dark 16

Object Destructuring

Object destructuring pulls values out by property name instead of position.

javascript
const user = { name: "Sam", age: 31 };
const { name, age } = user;
console.log(name, age);
// Sam 31

Renaming lets you assign the value to a different variable name using a colon.

javascript
const user = { name: "Sam", age: 31 };
const { name: userName } = user;
console.log(userName);
// Sam

Default values work the same way as with arrays, using =, and apply when the property is missing.

javascript
const user = { name: "Sam" };
const { role = "guest" } = user;
console.log(role);
// guest

Renaming and defaults can be combined.

javascript
const user = { name: "Sam" };
const { name: userName, role: userRole = "guest" } = user;
console.log(userName, userRole);
// Sam guest

The Spread Operator (...)

The spread operator expands an array or object into its individual items. Written before a value inside [] or {}, it’s most often used for copying and merging.

Copying an array:

javascript
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);

console.log(original);
// [ 1, 2, 3 ]
console.log(copy);
// [ 1, 2, 3, 4 ]

copy is a brand new array. Changing it doesn’t touch original.

Merging arrays:

javascript
const morning = ["Erin", "Jordan"];
const afternoon = ["Maya", "Priya"];
const everyone = [...morning, ...afternoon];

console.log(everyone);
// [ 'Erin', 'Jordan', 'Maya', 'Priya' ]

Copying an object works the same way, with {}.

javascript
const defaults = { theme: "light", notifications: true };
const copy = { ...defaults };
copy.theme = "dark";

console.log(defaults);
// { theme: 'light', notifications: true }
console.log(copy);
// { theme: 'dark', notifications: true }

Merging objects, where later properties override earlier ones with the same key:

javascript
const defaults = { theme: "light", notifications: true };
const overrides = { theme: "dark" };
const settings = { ...defaults, ...overrides };

console.log(settings);
// { theme: 'dark', notifications: true }

Rest Syntax (...)

Rest syntax looks identical to spread, three dots, but does the opposite job: instead of expanding values out, it gathers the leftover values into one array or object. This is the same rest syntax you used for function rest parameters in Module 4, just collecting leftover array or object items here instead of leftover arguments.

In array destructuring, rest collects everything after the variables you named.

javascript
const scores = [95, 88, 76, 60];
const [top, ...rest] = scores;

console.log(top);
// 95
console.log(rest);
// [ 88, 76, 60 ]

In object destructuring, rest collects the remaining properties into a new object.

javascript
const user = { name: "Jordan Reyes", age: 34, role: "admin" };
const { name, ...otherDetails } = user;

console.log(name);
// Jordan Reyes
console.log(otherDetails);
// { age: 34, role: 'admin' }

The rule for telling spread and rest apart isn’t the dots, it’s the position: spread expands values on the side where a value is being built up (an array or object literal), rest gathers values on the side where a pattern is being matched (a destructuring assignment).

Try It

  1. Given const pair = [3, 7], destructure it into first and second and log both.
  2. Given const config = ["dark"], destructure it into theme and fontSize, giving fontSize a default of 14.
  3. Given const person = { name: "Maya", city: "Nairobi" }, destructure name renamed to fullName, and country with a default of "Unknown".
  4. Given const a = [1, 2] and const b = [3, 4], use spread to build a single merged array.
  5. Given const base = { volume: 5 } and const custom = { volume: 8, muted: false }, merge them with spread so custom’s values win.
  6. Given const numbers = [1, 2, 3, 4, 5], use rest destructuring to capture the first number separately from the rest.

Recap

  • Array destructuring pulls values out by position; object destructuring pulls values out by property name.
  • Both support default values, and object destructuring supports renaming with :.
  • Spread (...) expands an array or object into a new one, useful for copying and merging.
  • Rest (...) gathers leftover items during destructuring, the same idea as the rest parameters from Module 4, applied to arrays and objects instead of function arguments.

Next lesson: nested objects, and how to safely read a property that might not exist.