DEV Community

Cover image for Beginner's Guide To ES6 Destructuring
Marc Backes
Marc Backes

Posted on โ€ข Edited on โ€ข Originally published at developer.blog

13 5

Beginner's Guide To ES6 Destructuring

Cross-posted from developer.blog ๐Ÿฅณ

ES6 comes with a bunch of new features, one of which is destructuring. This is a very handy way to extract items from objects and arrays which -once understood- can make your code much cleaner and more readable.

Let's get started!

First things first โ˜๏ธ

In this post we'll see lots of code that looks like the following:

const { property1, property2 } = object
Enter fullscreen mode Exit fullscreen mode
  • The left-hand side are the variables being assigned
  • The right-hand side is the source where the information comes from

Destructuring objects ๐Ÿ“ฆ

Let's assume we have an object movie which contains id, title, year as properties:

const movie = {
    id: 99,
    title: 'The Matrix',
    year: 1999
}
Enter fullscreen mode Exit fullscreen mode

If we were to extract the properties of this object the old-fashioned way, we'd have to do something like this:

const id = movie.id
const title = movie.title
const year = movie.year
Enter fullscreen mode Exit fullscreen mode

To make your code more readable, you can use the ES6 way:

const { id, title, year } = movie
console.log(id, title, year); // 99 The Matrix 1999
Enter fullscreen mode Exit fullscreen mode

You'll get exactly the same result as in the example with 3 lines of code. As a result you have three variables id, title, year which each contain the respective value from the object movie.

It's important to know that the variable name and the object property have to be the same!

Using a different variable name

If you can't or don't want to use the same variable name as property (e.g. if you have already a variable with that name in use), you can add a colon and indicate the desired variable name:

const { originalPropertyName:newPropertyName } = object

// Example ๐Ÿ‘‡
const { title:movieTitle, year:releaseYear } = movie
Enter fullscreen mode Exit fullscreen mode

Defining a default value

If you're in the situation you want to fill in a default value in case a destructed property is undefined, you can add = followed by the default value:

const { title, rating = 3 } = movie
Enter fullscreen mode Exit fullscreen mode

We didn't define a rating property in our movie object, so it would normally be undefined. But as we used the default value syntax, the rating variable would have 3 in case it's not yet.

Use destructing in a function parameter

const printMovie = ({ title, year, rating }) => {
    // Work directly with the destructed properties
    console.log(`The movie ${title} (${title}) has a ${rating} rating`)
    console.log(`โญ๏ธ`.repeat(Math.floor(rating)))
}
Enter fullscreen mode Exit fullscreen mode

Extracting from nested objects

If you have nested objects, you can apply the same principle, only ... well nested.

const character = {
    movie: 'The Matrix',
    name: 'Thomas A. Anderson',
    alias: 'Neo',
    actor: {
        firstname: 'Keanu',
        lastname: 'Reeves'
    }
}
Enter fullscreen mode Exit fullscreen mode

If you'd be interested in only the actor of this movie character, you can apply nested destructuring:

const { actor: { firstname, lastname } } = character
console.log(firstname, lastname) // Keanu Reeves
Enter fullscreen mode Exit fullscreen mode

Destructuring arrays โ›“

ES6 also defines some nifty ways of destructuring arrays.

Let's take a look at the old way first:

const food = ['๐Ÿ•', '๐ŸŒญ', '๐Ÿ”', '๐Ÿ', '๐Ÿ“']
const pizza = food[0]
const hotdog = food[1]
const burger = food[2]
console.log(pizza, hotdog, burger) // ๐Ÿ• ๐ŸŒญ ๐Ÿ”
Enter fullscreen mode Exit fullscreen mode

In ES6, you can get the values as such:

const food = ['๐Ÿ•', '๐ŸŒญ', '๐Ÿ”', '๐Ÿ', '๐Ÿ“']
const [pineapple, strawberry] = food
console.log(pineapple, strawberry) // ๐Ÿ ๐Ÿ“
Enter fullscreen mode Exit fullscreen mode

What might be interesting to know:

You can destructure anything that is iterable. That includes String.

const fruitSalad = '๐Ÿ๐ŸŒ๐Ÿ๐Ÿ’๐Ÿ‡'
const [s, a, l, a, d] = fruitSalad
console.log(d,a,l,a,s) // ๐Ÿ‡๐Ÿ’๐Ÿ๐ŸŒ๐Ÿ
Enter fullscreen mode Exit fullscreen mode

Ignoring items in an array

When destructuring an array, you can ignore values that might not be of interest to you. Also: You can skip as many items as you want.

const breakfast = ['๐Ÿฅ','๐Ÿณ', '๐Ÿง€','๐Ÿฅ“', '๐Ÿฅ–']

const [croissant, eggs,, bacon] = breakfast
console.log(croissant, eggs, bacon) // ๐Ÿฅ๐Ÿณ๐Ÿฅ“

const [,,cheese,,baguette] = breakfast
console.log(cheese, baguette) // ๐Ÿง€๐Ÿฅ–
Enter fullscreen mode Exit fullscreen mode

Using the rest operator

If you have an array where you want to get certain items in variables and the rest in a separate array, you can use the spread syntax (...rest):

const food = ['๐Ÿฅ', '๐Ÿฅž', '๐Ÿฅฆ', '๐Ÿ†', '๐Ÿ…']
const [croissant, pancakes, ...veggies] = food
console.log(croissant, pancakes) // ๐Ÿฅ๐Ÿฅž
console.log(veggies) // ["๐Ÿฅฆ", "๐Ÿ†", "๐Ÿ…"]
Enter fullscreen mode Exit fullscreen mode

Swapping variables using destructuring

A handy trick for swapping variables is, using destructuring to do so. Let's assume you have variables x and y, having each a value:

let x = 4711
let y = 1337
Enter fullscreen mode Exit fullscreen mode

To swap them, you could to it by using a temporary variable:

let temp = x
x = y
y = temp
Enter fullscreen mode Exit fullscreen mode

But that's not clean or readable. ES6 destructuring gives a great way to swap these numbers:

[x, y] = [y, x]
console.log(x, y) // 1337 4711
Enter fullscreen mode Exit fullscreen mode

Summary ๐Ÿ™Œ

As you see in the examples, destructuring is a great way to make your code shorter and better readable. So whenever you find yourself repeating something like

this.value1 = anotherObject.value1
this.value2 = anotherObject.value2
this.value3 = anotherObject.value3
this.value4 = anotherObject.value4
Enter fullscreen mode Exit fullscreen mode


`
you have an opportunity to apply destructuring.

So, head on to your latest pet project and check if there is anywhere you can apply this knowledge ๐Ÿ˜Š

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly โ€” using the tools and languages you already love!

Learn More

Top comments (5)

Collapse
 
donaldkelly17 profile image
Donald Kelly โ€ข

I love the article. Heard of descructuring before but never really understood it until now. Thanks for posting. Just one comment about this bit of code:

  const food = ['๐Ÿ•', '๐ŸŒญ', '๐Ÿ”', '๐Ÿ', '๐Ÿ“']
  const [pineapple, strawberry] = food
  console.log(pineapple, strawberry) // ๐Ÿ ๐Ÿ“

Would this not console log the Pizza and Hotdog? Or need to add three commas to the destructuring before pineapple to ignore the first three items - as you discuss later - if pineapple and strawberry is required.

Collapse
 
themarcba profile image
Marc Backes โ€ข

Hi! I'm happy that my content helps you understanding JavaScript. That's nice to hear.

Indeed you're right about the pizza and the hotdog. My example on that part was wrong. I corrected it. Thanks for pointing it out!

Collapse
 
samelawrence profile image
Sam E. Lawrence โ€ข

This post is great, but I think some of your code formatting got out of whack at the end there.

Collapse
 
themarcba profile image
Marc Backes โ€ข

Thanks for the heads up. Fixed two instances where I found formatting problems.

Collapse
 
themarcba profile image
Marc Backes โ€ข

Youโ€™re most welcome ๐Ÿ˜Š

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

๐Ÿ‘‹ Kindness is contagious

If this post resonated with you, feel free to hit โค๏ธ or leave a quick comment to share your thoughts!

Okay