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>