-2

I had this code:

const availableDays = status.availableDays;

And I had a suggestion to change with:

const { availableDays } = status;

They both are one line code, but I wonder if there is an explanation on why would be the destructuring a better way to code than the first one.

If the code would be:

const availableDays = status.availableDays;
const someVar = status.someVar;
const someOtherVar = status.someOtherVar;

I know that would be shortest (don't know if better) this way:

const { availableDays, someVar, someOtherVar } = status;

But my question goes to a performance, security, readability, etc reason.

pmiranda
  • 7,602
  • 14
  • 72
  • 155

2 Answers2

1

The advantage is in not repeating the identifier, which is the same for the property name and the variable.

This makes the code more concise, easier to read/understand, and reduces the potential for spelling mistakes. There is no difference to performance (if not counting code size) or security (if not counting bug likelihood).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Here is an example of the improved readability:

const myObj = { availableDays: 3, someVar: "foo", someOtherVar: "bar" };

function myFunc(status) {
   const availableDays = status.availableDays;
   const someVar = status.someVar;
   const someOtherVar = status.someOtherVar;

   // do stuff
}

Can be refactored to:

function myFunc({ availableDays, someVar, someOtherVar }) {
   // do stuff
}

This is especially useful when dealing with prop passing into React components.

zr0gravity7
  • 2,917
  • 1
  • 12
  • 33