Unpack arrays and objects; copy and merge.
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
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