DMarlon Studio

Lesson 16 · 16 of 20

Destructuring and spread · JavaScript

Unpack values from arrays and objects with JavaScript destructuring, and copy or combine data with the spread operator (...).

JavaScript · Destructuring and spread in DMarlon Studio: the example's code and its output in the terminal

Destructuring takes values out of an array and stores them in variables in one go. const [gold, silver, bronze, ...rest] = podium takes the first three drivers in order and, with ...rest, puts the others in another array.

The same idea swaps two variables without a temporary one: [home, away] = [away, home] builds an array with the values swapped round and destructures it into the same variables.

Objects are destructured by name, not by position: const { name, level } = player creates the variables name and level with those values. If a property does not exist, it can get a default value, like lives = 3.

Destructuring also works in a function's parameters, ({ name, coins }) =>, and in a for...of: Object.entries() returns [key, value] pairs and [item, qty] splits them.

The spread operator ... does the opposite: it unpacks an array or object. [...weekA, ...weekB, 30] joins two arrays and adds a value, Math.max(...scores) passes each number as a separate argument and { ...player, level: 13 } copies the object while changing some properties, leaving the original alone. It is the pattern React uses to update its state.

Code · main.js

// Array destructuring: take the values out by position.const podium = ["Lewis", "Max", "Charles", "Lando", "Oscar"];const [gold, silver, bronze, ...rest] = podium;console.log(`Gold: ${gold}, silver: ${silver}, bronze: ${bronze}`);console.log("The rest:", rest);// Swap two variables without a temporary one.let home = 2;let away = 3;[home, away] = [away, home];console.log("Swapped score:", home, "-", away);// Object destructuring: take the values out by name.const player = { name: "Nora", level: 12, coins: 340 };const { name, level, lives = 3 } = player; // lives gets a defaultconsole.log(`${name} is on level ${level} with ${lives} lives`);// Destructuring in parameters and in for...ofconst describe = ({ name, coins }) => `${name} has ${coins} coins`;console.log(describe(player));for (const [item, qty] of Object.entries({ swords: 2, potions: 5 })) {  console.log(`  ${item}: ${qty}`);}// Spread (...) unpacks arrays and objects to copy or combine them.const weekA = [12, 15];const weekB = [9, 20];const scores = [...weekA, ...weekB, 30];console.log("All scores:", scores, "| Best:", Math.max(...scores));const upgraded = { ...player, level: 13, coins: player.coins + 50 };console.log("Before:", player);console.log("After: ", upgraded);

Output · node main.js

Gold: Lewis, silver: Max, bronze: Charles
The rest: [ 'Lando', 'Oscar' ]
Swapped score: 3 - 2
Nora is on level 12 with 3 lives
Nora has 340 coins
  swords: 2
  potions: 5
All scores: [ 12, 15, 9, 20, 30 ] | Best: 30
Before: { name: 'Nora', level: 12, coins: 340 }
After:  { name: 'Nora', level: 13, coins: 390 }

Key points

  • const [a, b] = array unpacks by position.
  • const { x, y } = object unpacks by name.
  • ...rest collects whatever is left.
  • [...a, ...b] and { ...obj, key: value } copy and combine without changing the original.

Exercise

Use destructuring to get the first and fourth drivers, skipping the others with commas (const [winner, , , fourth] = podium), and make a copy of player with 100 more coins and a new team property.