Destructuring
While returning objects from functions is powerful, it can be annoying to continually use the dot (.) operator to extract the values you need on the receiving end.
The destructuring assignment allows you to “unpack” an object’s properties directly into local variables.
Standard vs Destructured
Instead of assigning variables one by one:
const apple = {
radius: 2,
color: "red",
};
// Tedious extraction
const radius = apple.radius;
const color = apple.color;
You can destructure the object in a single line. The curly braces on the left side of the equals sign tell JavaScript to look inside the apple object and create standalone variables matching those key names.
const apple = {
radius: 2,
color: "red",
};
// Clean extraction
const { radius, color } = apple;
console.log(color); // Output: "red"
Destructuring Function Returns
This pattern is most commonly seen when unpacking the returned object from a function call immediately:
function getMetrics() {
return { opened: 800, sent: 1000 };
}
// Immediately unpack the returned object
const { opened, sent } = getMetrics();
console.log(opened); // 800
Destructuring Parameters
Destructuring also works directly inside function signatures. If a function takes an object as an argument, you can unpack it right in the parameter definition!
// Normal
function eatApple(appleObj) {
console.log(`Ate a ${appleObj.color} apple.`);
}
// Destructured
function eatAppleDestructured({ color }) {
console.log(`Ate a ${color} apple.`);
}