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
- 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
}
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
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
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
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
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)))
}
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'
}
}
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
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) // π π π
In ES6, you can get the values as such:
const food = ['π', 'π', 'π', 'π', 'π']
const [pineapple, strawberry] = food
console.log(pineapple, strawberry) // π π
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) // πππππ
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) // π§π₯
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) // ["π₯¦", "π", "π
"]
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
To swap them, you could to it by using a temporary variable:
let temp = x
x = y
y = temp
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
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
`
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)
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:
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.
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!
This post is great, but I think some of your code formatting got out of whack at the end there.
Thanks for the heads up. Fixed two instances where I found formatting problems.
Youβre most welcome π