Destructuring in For-Of Loops
You'll learn how to extract object properties directly while iterating through arrays of objects, making your loop code cleaner and more readable.
The Core Idea
When you have an array of objects and need to loop through them, you can destructure each object right in the for...of loop declaration instead of accessing properties with dot notation inside the loop body. This eliminates repetitive property access and makes your intent crystal clear.
Think of it like unpacking a delivery box at your doorstep instead of carrying the entire box inside and unpacking it there—you immediately have what you need.
How It Works
Instead of writing:
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
];
for (const user of users) {
console.log(user.name, user.age);
}
You can destructure directly in the loop:
for (const { name, age } of users) {
console.log(name, age);
}
The { name, age } extracts those properties from each object as the loop iterates.
With Renaming and Defaults
You can also rename variables and provide defaults:
const products = [
{ title: 'Laptop', price: 999 },
{ title: 'Mouse' } // missing price
];
for (const { title: productName, price = 0 } of products) {
console.log(`${productName} costs $${price}`);
}
// "Laptop costs $999"
// "Mouse costs $0"
This combines everything you've learned: destructuring syntax, renaming with colons, and default values—all working together in a loop context.
Key Takeaway: Destructuring in for...of loops lets you extract object properties directly in the loop declaration, reducing clutter and improving code clarity when iterating over arrays of objects.