JavaScript Destructuring & Spread

Unpack arrays and objects; copy and merge.

✍️ 3 exercises + code challenge in this lesson

Destructuring

Unpack values into variables in one line:

  • Arrays: const [first, second] = list;
  • Objects: const { name, age } = person; with defaults { city = "Lahore" } and renaming { name: fullName }

Spread and rest (...)

  • Spread expands: [...a, ...b], { ...defaults, ...options }
  • Rest collects: function sum(...numbers)

Key Takeaways: JavaScript Destructuring & Spread

Mastering JavaScript Destructuring & Spread helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Destructuring & Spread Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
const [gold, silver, ...others] = ["Ali", "Sara", "Usman", "Ayesha"];
log("Gold:", gold, "| Silver:", silver, "| Others:", others);

const user = { name: "Hina", age: 23 };
const { name, age, city = "Karachi" } = user;
log(name, age, city);

const defaults = { theme: "light", lang: "en" };
const settings = { ...defaults, theme: "dark" };
log(JSON.stringify(settings));

const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
log("sum:", sum(1, 2, 3, 4));
</script>
Free sign-in required · Google login available

JavaScript Destructuring & Spread Practice Exercises

Check what you learned in “JavaScript Destructuring & Spread”.

/ 3 solved
Fill in the blank

Unpack name and age from the object.

const { ,  } = person;
✓ Correct! Not quite. Try again.
Multiple choice

What does [...a, ...b] do?

✓ Correct! Not quite. Try again.
Code challenge

Use array destructuring to take the first two items of list into first and second, then log them separated by a space.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services