JS Refactoring Combo: Introduce Object Destructuring

Lars Grammel - Jun 8 '22 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player