Destructuring is a way to access array values or object properties. It can be used in variable declarations, parameters, and catch clauses.
You can use destructuring to access several properties at once, making it possible to concisely unpack an object into local variables. These local variables can replace redundant property access chains and make the code easier to read.
Before (Example)
for (const item of items) {
totalAmount += item.price.amount - item.price.discount;
totalDiscount += item.price.discount;
logPurchase(
item.customer.country,
item.customer.zipCode,
item.price.amount
);
}
Refactoring Steps
💡 The refactoring steps are using P42 JavaScript Assistant v1.113
- Extract all occurrences of the object properties into a variable for each property. The name of the variables should match the property names.
- Convert the variables to destructuring expressions.
- Move up the variables so that they are next to each other.
- Merge the destructuring expressions.
- Push the combined destructuring expression into the destructured variable (optional).
After (Example)
for (const { price, customer } of items) {
totalAmount += price.amount - price.discount;
totalDiscount += price.discount;
logPurchase(
customer.country,
customer.zipCode,
price.amount
);
}