DEV Community

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

Posted on • Edited on • Originally published at developer.blog

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 😊

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 😊