DEV Community

Cover image for JS Refactoring Combo: Introduce Object Destructuring
Lars Grammel for P42

Posted on • Updated on • Originally published at p42.ai

JS Refactoring Combo: Introduce Object Destructuring

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
  );
}

Enter fullscreen mode Exit fullscreen mode

Refactoring Steps

Introduce object destructuring

💡  The refactoring steps are using P42 JavaScript Assistant v1.113

  1. Extract all occurrences of the object properties into a variable for each property. The name of the variables should match the property names.
  2. Convert the variables to destructuring expressions.
  3. Move up the variables so that they are next to each other.
  4. Merge the destructuring expressions.
  5. 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
  );
}
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
pengeszikra profile image
Peter Vivo • Edited on

Imho that for loop use too much side effect.

const countTotals = ({price:{amount, discount}}) => {
  totalAmount += amount - discount;
  totalDiscount += discount;  
};

const logSummary = ({price:{amount}, customer:{country, zipCode}}) => 
  logPurchase(country, zipCode, amount);

items.forEach(countTotals);
const logResults = items.map(logSummary);
Enter fullscreen mode Exit fullscreen mode
Collapse
lgrammel profile image
Lars Grammel Author

The for loop is not the point, it is an example. This blog post is about describing a technique to introduce destructuring safely with automated refactorings in situations where you might want to.