Why I Find JavaScript’s ES6 Destructuring So Fascinating

I spend a lot of time in PHP land.

PHP is a very useful and competent language, but I feel it’s fair to say it lacks somewhat in syntactical grace.

JavaScript’s ES6 on the other hand, is very elegant (to my eyes). This is a snippet from a React tutorial I have been following recently.

  const {
    isFetching,
    lastUpdated,
    items: posts
    } = postsBySubreddit[selectedSubreddit] || {
    isFetching: true,
    items: []
  };

There’s so much going on here.

As a recent migrant to ES6, I find this as intriguing as I do confusing.

The primary concept at work here is ES6 Destructuring. This is a really interesting technique to pull multiple pieces of data from arrays or objects in one go.

I found the concept initially confusing. I read this as a const  that is an object but has no variable name? Not quite.

It’s somewhat easier to understand this statement if we break it down one step further:

  const {
    isFetching,
    lastUpdated,
    items: posts
    } = postsBySubreddit[selectedSubreddit];

I still feel this is complicated for someone, like me, who is new to Destructuring.

Let’s take an even simpler example:

const {a} = {a: 1, b: 2};

This looks a bit easier, a bit more understandable, I feel.

Here we have a regular JavaScript object: {a: 1, b: 2}

We want to create ourselves a constant containing the value of a from this object. A test might illustrate this a little better than words:

it('is possible to grab "a" from our object', () => {
  const ourObject = {a: 1, b: 2};
  let a = ourObject.a; 
  assert.equal(a, 1);
});

Destructuring gives us a short hand notation for this same concept:

it('is possible to grab "a" from our object in a more concise way', () => {
  const {a} = {a: 1, b: 2};
  assert.equal(a, 1);
});

By using the same key name inside the {} ‘s as that which exists on the object, ES6 will go ahead and create us a constant, called a with the value of 1. It essentially pulls out the value from the object and creates a variable / constant for us. Two steps, combined into one. This is one of those things I have immediately started to miss the most when working in PHP.

But what if we don’t want the new constant to be called a, but we do want it to still contain the value of a. Of course, ES6 has you covered here too:

it('is possible to rename "a"', () => {
  const {a: somethingElse} = {a: 1, b: 2};
  assert.equal(somethingElse, 1);
});

Seems a little back to front, but it does make sense. Pull out a as we’ve already covered, and re-name it to somethingElse.

You can see this in action in the React tutorial snippet:

  const {
    isFetching,
    lastUpdated,
    items: posts
    } = postsBySubreddit[selectedSubreddit];

Here, items exists in the original data, and whilst we do want to use the value of items, we want to use a different reference for it – posts.

There are other things we could do with destructuring assignment, it really is quite an awesome concept.

Now we know about these two concepts, let’s take another look at the example:

  const {
    isFetching,
    lastUpdated,
    items: posts
    } = postsBySubreddit[selectedSubreddit];

So we can see both of the above (pulling out by name, and pull-out-and-rename) happening in one statement here.

I found the postsBySubreddit name really confused me. If you can, disregard the name, and simply think of it as an object:

someObject[dynamicKey]

Then for me, it becomes a little easier to reason about:

  it('is possible to use a dynamic key', () => {
    
    let dynamicKey = 'key2';

    const someObject = {
      key1: 'a',
      key2: 'b',
      key3: 'c'
    };
    
    assert.equal(someObject[dynamicKey], 'b');
  });

postsBySubreddit is simply an object with potentially multiple keys.Each key will be the name of a subreddit: ‘php’, ‘reactjs’, ‘programming’ and so on.

We aren’t hard-coding the value of the key we need. We are instead asking for a key using the variable named selectedSubreddit, or dynamicKey in my example.

Don’t just take my word for this though, do look at the code. Unfortunately, I can’t link directly to the line(s) in question, but a quick ctrl+f on the linked page for ‘postsBySubreddit’ will get you to where you need to be.

selectedSubreddit will be one of these keys / subreddits. And all subreddit data will be an array, called items. But because we know that destructuring can rename a property for us, we can take advantage of this to rename items to posts .

isFetching and lastUpdated are both straightforward (in as much as any of this is straightforward), in that they are keys we want to create constants for.

Phew, that’s a lot happening in one statement.

But, remember, we actually broke this line down even further:

  const {
    isFetching,
    lastUpdated,
    items: posts
    } = postsBySubreddit[selectedSubreddit] 
  || {
    isFetching: true,
    items: []
  };

At this stage, we are really only concerned with the bit we haven’t yet covered, so I’ve reformatted it slightly to make it more obvious.

So we’ve done all this destructuring… OR (||) if we are unable to access postsBySubreddit[selectedSubreddit]  then create two constants:

isFetching: true,
items: []

Which would leave lastUpdated as undefined.

But don’t just take my word for it. Have a play around with this code and get a feel for what it is doing. Destructuring is definitely something you will start using more and more, but it’s initially confusing for sure.

JavaScript is moving fast (although I have heard some say that this is slowing down) and if you’re still finding your feet with PHP (or any other language) then I’d advise not to dig to deeply into ES6 just yet.

I’d argue that the transition to ES6 is going to be so challenging for some developers that we may possibly end up in a Python 2 / 3 situation in JavaScript land in the next few years. Which is why I believe the current form of JavaScript will be around for years to come.

Whichever form of JavaScript you choose to use, take the time to dig into the more functional concepts of JavaScript. It will truly help your programming – including your PHP – skills grow.

Basic React ES6 Class Example

Sometimes it’s the super easy stuff I forget how to do.

It’s really straightforward to create a WebStorm Live Template for a React ES6 Class template.

But when you’re first starting to learn things like this, I find just repeatadly typing it out every time I want to make a new React ES6 class really helps grind it into my memory:

import React from 'react';

class YourClassNameHere extends React.component {

  render() {
    return (
      <div className="yourCssClassName">

      </div>
    );
  }

}

YourClassNameHere.propTypes = {
  pair: React.PropTypes.array.isRequired
};

export default YourClassNameHere;