Introduction
JavaScript has some features that look confusing at first, but once you get them, they make your code much better. Destructuring and spread/rest are two such features. They help you write less code, avoid repetition, and keep things clean.
1. What is Destructuring?
Destructuring means picking values from arrays or objects and storing them directly into variables.
Array Destructuring
const colors = ['red', 'green', 'blue'];
const [first, second] = colors;
console.log(first); // red
console.log(second); // green
You are extracting values from the array without using colors[0], colors[1], etc.
You can skip values too.
const [ , , third] = colors;
console.log(third); // blue
Object Destructuring
const user = {
name: 'Diksha',
age: 25,
city: 'Delhi',
};
const { name, city } = user;
console.log(name); // Diksha
console.log(city); // Delhi
You directly extract values from the object without repeating the user.name, user, city.
You can also rename them.
const { name: userName } = user;
console.log(userName); // Diksha
2. What is the Spread Operator (...)
Spread takes all values from an array or object and spreads them somewhere else.
Array Spread
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2];
console.log(merged); // [1, 2, 3, 4]
This is better than writing a loop or using .concat().
You can also copy an array like this.
const copy = [...arr1];
Object Spread
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const combined = { ...obj1, ...obj2 };
console.log(combined); // { a: 1, b: 2 }
If both objects have the same key, the last one wins.
3. What is the Rest Operator (...)
Rest looks the same as spread, but it works in reverse. It collects the remaining values.
Array Rest
const [first, ...rest] = [10, 20, 30];
console.log(first); // 10
console.log(rest); // [20, 30]
One variable takes the first value. The rest goes into an array.
Object Rest
const person = {
id: 1,
name: 'Diksha',
role: 'Developer'
};
const { name, ...others } = person;
console.log(name); // Diksha
console.log(others); // { id: 1, role: 'Developer' }
You separate one key, and keep the rest grouped.
Real Use in Projects
- Use destructuring when working with API responses or function arguments.
- Use spread to copy arrays or objects, or to merge them.
- Use rest in functions where you don’t know how many arguments will come.
Example
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6
Conclusion
In short, destructuring helps you avoid repetitive code, spread copies or merge values, and rest collects values together.