Learn the concept
Destructuring
Destructuring extracts values from arrays or properties from objects into distinct variables. The spread operator (...) expands iterables into individual elements, while rest (...) collects remaining elements into an array or object.
Destructuring (ES6) unpacks values from arrays or objects:
Array destructuring:
Object destructuring:
Spread operator (...):
Rest operator (...):
// Array destructuring
const [first, second, third] = [1, 2, 3];
const [a, , c] = [1, 2, 3]; // skip second: a=1, c=3
const [x = 10, y = 20] = [1]; // defaults: x=1, y=20
// Object destructuring
const { name, age } = { name: 'Alice', age: 25 };
const { name: userName } = { name: 'Alice' }; // rename
const { role = 'user' } = {}; // default value
// Nested destructuring
const { address: { city } } = {
address: { city: 'NYC', zip: '10001' }
};
console.log(city); // 'NYC'
// In function parameters
function greet({ name, greeting = 'Hello' }) {
return `${greeting}, ${name}!`;
}
greet({ name: 'Alice' }); // 'Hello, Alice!'Destructuring props in function components for cleaner code: function Card({ title, body })
Using spread to create copies of state objects before modification in React and Redux
Destructuring nested API responses to extract only the relevant data fields needed by components
Build a utility that deep-merges configuration objects using spread and destructuring
Transform nested API responses into flat, component-ready data structures using destructuring