agyanadda@gmail.com

JS Destructuring and Spread

Arrays and Objects 1 min read Updated Dec 1, 2026 Topic 23 of 38

Array destructuring

const [first, second] = ['Red', 'Green', 'Blue'];

Object destructuring

const { name, age } = student;
const { name: studentName } = student; // rename
const { city = 'Unknown' } = student;  // default

Spread ...

Spreads items out:

  • Copy / merge arrays: [...a, ...b]
  • Copy / merge objects: { ...defaults, ...options }
  • Pass array as arguments: Math.max(...nums)

Rest ...

Collects the rest into an array:

function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }

Example

Example — Destructuring and spread HTML
<pre id="out"></pre>

<script>
  const user = { name: 'Ravi', role: 'Student', city: 'Patna' };
  const { name, role, country = 'India' } = user;

  const [gold, silver, ...others] = ['Neha', 'Asha', 'Aman', 'Ravi'];

  const updated = { ...user, role: 'Mentor' };
  const sum = (...n) => n.reduce((a, b) => a + b, 0);

  document.getElementById('out').textContent = [
    `${name} – ${role} – ${country}`,
    `Gold: ${gold}, Silver: ${silver}, Others: ${others.join(', ')}`,
    'Updated role: ' + updated.role + ' (original: ' + user.role + ')',
    'Sum: ' + sum(5, 10, 15),
    'Max: ' + Math.max(...[4, 19, 7])
  ].join('\n');
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

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

Exercise 2 True / False

const { name } = user; creates a variable called name.

Exercise 3 Fill in the Blank

The spread and rest syntax both use three ___.

Frequently Asked Questions

No, a shallow copy. Nested objects are still shared. Use structuredClone(obj) for a deep copy.