Destructuring

  • 5.1 Use object destructuring when accessing and using multiple properties of an object. eslint: prefer-destructuring

    Why? Destructuring saves you from creating temporary references for those properties.

    1. // bad
    2. function getFullName(user) {
    3. const firstName = user.firstName;
    4. const lastName = user.lastName;
    5. return `${firstName} ${lastName}`;
    6. }
    7. // good
    8. function getFullName(user) {
    9. const { firstName, lastName } = user;
    10. return `${firstName} ${lastName}`;
    11. }
    12. // best
    13. function getFullName({ firstName, lastName }) {
    14. return `${firstName} ${lastName}`;
    15. }

  • 5.2 Use array destructuring. eslint: prefer-destructuring

    1. const arr = [1, 2, 3, 4];
    2. // bad
    3. const first = arr[0];
    4. const second = arr[1];
    5. // good
    6. const [first, second] = arr;

  • 5.3 Use object destructuring for multiple return values, not array destructuring.

    Why? You can add new properties over time or change the order of things without breaking call sites.

    1. // bad
    2. function processInput(input) {
    3. // then a miracle occurs
    4. return [left, right, top, bottom];
    5. }
    6. // the caller needs to think about the order of return data
    7. const [left, __, top] = processInput(input);
    8. // good
    9. function processInput(input) {
    10. // then a miracle occurs
    11. return { left, right, top, bottom };
    12. }
    13. // the caller selects only the data they need
    14. const { left, top } = processInput(input);