Destructuring objects and arrays is probably the most used feature in ES6 and for good reason. This simple technique is amazing for writing cleaner, more readable JavaScript code. Another cool feature that also shipped with ES6 is variable renaming. The only problem with this is that it can cause some confusion to coders who are still getting to grips with everything that modern JavaScript has to offer. Let’s take a look at these two concepts in practice and show you where pitfalls commonly occur.

Basic Destructuring in Practice

Imagine we have a person object that has the keys name and surname declared like this:

const person = {

name: 'Barry',

surname: 'Doyle',

};

If you want to log the name and surname of person to the console the old fashioned way you would do this:

console.log(person.name, person.surname); // Barry Doyle

But because we’re all big fans of DRY (Don’t Repeat Yourself) we can use ES6 to destructure name and surname from person like this:

const { name, surname } = person; console.log(name, surname); // Barry Doyle

This obviously takes more lines to write so it might not be ideal right now. But it helps a lot when you start working with larger objects. As a general rule of thumb, if destructuring stops you from repeating yourself then use it! Otherwise don’t bother, it’s not worth it. For example, if we only wanted to log name to the console then I would highly discourage the use of destructuring for just one variable.

Deeper Nested Destructuring

I gave you a simple example above. Let’s check out something a little more complicated. What if we had an object of objects? Imagine I extended my person object to include a key called skills which is an object of keys representing some of my skills. For the purpose of this example I’m just going to give my skills object two keys: JavaScript and React . Each of these keys will have the value of an object with one key inside. This key for each of my objects will be years which represent the years of experience I have in the object’s key. Here’s the declaration of our new extended person object:

const person {

name: 'Barry',

surname: 'Doyle',

skills: {

JavaScript: {

years: 7,

},

React: {

years: 4,

},

},

};

Again, the old fashioned way of logging out my name , surname and experience in years for JavaScript and React respectively would be to do the following:

console.log(

person.name,

person.surname,

person.skills.JavaScript.years,

person.skills.React.years

); // Barry Doyle 7 4

Now using our wonderful ES6 destructuring technique we can simplify our console log like this:

const { name, surname, skills: { JavaScript, React } } = person; console.log(name, surname, JavaScript.years, React.years)

// Barry Doyle 7 4

This is a weird unusual example, but I hope you get the point. We could go further and destructure years from the JavaScript or React objects. However, we can’t get it from both of them because then we’d have one variable name pointing to two different values and that just won’t work. A work around for that is to rename the year variables as we destructure them.

Renaming Variables while Destructuring

Let’s take our example from above to assign the name javaScriptYears and reactYears to the years key assigned to the JavaScript and React objects respectively. To keep our code clean, I’m going to multi-line the destructuring statement.

const {

name,

surname,

skills: {

JavaScript: { years: javaScriptYears },

React: { years: reactYears },

},

} = person; console.log(name, surname, javaScriptYears, reactYears);

// Barry Doyle 7 4

Using this technique we’ve avoided the duplicate variable name problem that we would have had by destructuring the two different years values from our person object. In order to rename a variable while destructuring it. You need to add a : after the variable that you’re destructuring followed by the variable name that you’d like to rename the destructured variable to.

Notice how we say years: javaScriptYears and not years: { javaScriptYears } . Doing the former renames years to javaScriptYears while doing the latter would mean that years is an object with a key javaScriptYears that you’re trying to destructure from years .

Destructuring can be done inside Methods

The best part about destructuring is that it can be done on the fly very easily. Let’s pretend we have an array of objects called people implemented as follows:

const people = [

{ name: 'Barry' },

{ name: 'Michael },

{ name: 'Doyle' },

];

Now let’s map through people and log each name out to the console the old fashioned way:

people.map(person => console.log(person.name));

// Barry

// Michael

// Doyle

Here’s how you do it the fancy ES6 way:

people.map(({ name }) => console.log(name));

// Barry

// Michael

// Doyle

It probably doesn’t look that amazing right now. But trust me, down the line these techniques really save a lot of time and make everything much easier to read when working with more complicated data structures.

A Common Pitfall and The Inspiration for this Post

As a full time React developer I often see fellow colleagues give up on destructuring in event handlers due to a little confusion between destructuring and renaming variables.

Check out this basic React component:

import React, { Component } from 'react';

// ^^^ Look! we're even destructuring in our imports :D export default class SimpleInput extends Component {

state = {

inputText: '',

} constructor(props) {

super(props);

this.handleInputChange = this.handleInputChange.bind(this);

} handleInputChange(event) {

this.setState({ inputText: event.target.value });

}

// ^^^ Our focus is going to be here render() {

return (

<input

onChange={this.handleInputChange}

value={this.state.inputText}

/>

);

// ^^^ Notice how we don't bother destructuring inputText

// ^^^ from this.state because it doesn't prevent "DRY"

}

}

This is a simple React component that doesn’t really do much. But hey! It works as it should. I want us to focus on the handleInputChange event handler.

A common mistake that people make when trying to destructure variables is that they do this:

handleInputChange({ target: value }) {

this.setState({ inputText: value });

}

And low and behold we get crazy errors when we try to do this. We then proceed to inevitably give up and go back to doing things the old fashioned way because it’s never let us down.

What’s wrong with this implementation?

Well, when we wanted to get value out of the target object we were actually renaming the target object to value . Remember, we needed to do this ({ target: { value } }) not ({ target: value }) .

We can take this destructure technique even further by renaming the destructured value variable to inputText and use another handy ES6 feature to make our code readability even easier on the eye by doing this:

handleInputChange({ target: { value: inputText } }) {

this.setState({ inputText });

}

I haven’t gone into this other feature in much detail but here’s the tl:dr;

({ inputText }) is the same as ({ inputText: inputText }) .

Conclusion

I hope this post has taught you something new or at least solidified your understanding of these popular ES6 techniques.

This post has been inspired by The Complete Software Developer’s Career Guide: How to Learn Programming Languages Quickly, Ace Your Programming Interview, and Land Your Software Developer Dream Job. This book is going for really cheap on the link provided and is worth far more than what you’d be paying for it. Hands down, it has been the most influential factor of my growth as a professional software developer to date!

If you’ve enjoyed this post please leave some likes or claps or whatever. Also be sure to follow me on Facebook, Twitter, Medium, YouTube and LinkedIn to keep updated with new content that I produce.

Now go out there and write epic code!