Using ES6 Destructuring to assign class properties

Destructuring assignment (MDN Reference) is one of the best new JS features (especially coupled with default arguments and the spread or rest operator). If you aren’t familiar with destructuring assignment, there are lots of great examples in the link above, but here are a few:

Arrays:

const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a, c); // 1 3

Objects:

const person = {
  id: 1,
  firstName: "John",
  lastName: "Smith",
};
const { firstName, lastName } = person;
console.log(`Hello ${firstName}!`); // Hello John!

You can also rename the target of object properties, if you don’t want to assign to a variable with the same name as the property name:

const person = {
  id: 1,
  firstName: "John",
  lastName: "Smith",
};
const { firstName: first, lastName: last } = person;
console.log(`Hello ${first}!`); // Hello John!

I learned recently from the destructuring spec that:

…each assignment target can be everything that is allowed on the left-hand side of a normal assignment

This means that you can assign class properties with destructuring using the same notion as our last example – changing the default assignment target:

class Foo { 
    constructor(obj) { 
        ({ foo: this.foo, bar: this.bar } = obj);
    }
    logFooBar() {
        console.log(`foo: ${this.foo}, bar: ${this.bar}`);
    }
}

const myFoo = new Foo({ foo: 'Hello', bar: 'World' });
myFoo.logFooBar();

This also works with plain objects:

const person = {
  id: 1,
  firstName: "John",
  lastName: "Smith",
};
const anotherObject = {};

({ firstName: anotherObject.first, lastName: anotherObject.last } = person);

Or even Arrays!

const person = {
  id: 1,
  firstName: "John",
  lastName: "Smith",
};
const name = [];

({ firstName: name[0], lastName: name[1] } = person);
console.log(name.join(' ')); // "John Smith"

Have any other destructuring tips? Leave them in the comments.

Leave a Reply