Beginner’s Guide to ES6 Destructuring

sixtus iwuchukwu
LearnFactory Nigeria
4 min readOct 12, 2020

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.

First things first ☝️

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

const { item1, item2 } = object
  • The left-hand side is 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 userwhich contains id age, name, as properties:

const user= {
id: 1,
name: 'sixtus',
age: 29,
}

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

const id = user.id
const name= user.name
const age= user.age

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

const { id, name, age} = user
console.log(id, name, age) // 1 ,sixtus, 29

You’ll get exactly the same result as in the example with 3 lines of code. As a result, you have three variables id, name, age which each contain the respective value from the object user.

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 { originalItemName: newItemName } = object// Example 👇
const { name: userName, age: userAge} = user

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 { age, skinColor= "fair"} = user

We didn’t define a skinColorproperty in our userobject, so it would normally be undefined. But as we used the default value syntax, the skinColor variable would have fair in case it's not yet.

Use destructing in a function parameter


const printUser = ({ name, age, skinColor}) => {
// Work directly with the destructed properties
console.log(`The userName is ${name}, ${age} years old with a skinColor of ${skinColor}`)
}

Extracting from nested objects

If you have nested objects, you can apply the same principle, only which is called a spread Operator

const character = {
movie: 'Money Heist',
name: 'sixtus C. iwuchukwu',
alias: 'Neo',
actor: {
firstname: 'proffessor',
lastname: 'donald',
},
}

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) // proffessor donald

Destructuring arrays ⛓

ES6 also defines some nifty ways of destructuring arrays.

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


const food = ['pizza', 'hotdog', 'beans', 'yam', 'strawberry']
const pizza = food[0]
const hotdog = food[1]
const beans= food[2]
console.log(pizza, hotdog, beans) // pizza, hotdog, beans

In ES6, you can get the values as such:

const food = ['pizza', 'hotdog', 'beans', 'yam', 'strawberry']
const [beans, strawberry] = food
console.log(beans, strawberry) //beans, strawberry

What might be interesting to know:

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

const great= 'hello'
const [a, b, c, d, e] = great
console.log(a,b,c,d,e) // hello

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 a= 1
let b= 2

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:

let a = 1;
let b = 2;

[a, b] = [b, a];
a; // => 2
b; // => 1
[a, b] = [b, a] is the destructuring assignment that swaps the variables a and b.At the first step, on the right side of the destructuring, a temporary array [b, a] (which evaluates to [2, 1]) is created.Then the destructuring of the temporary array occurs: [a, b] = [2, 1]. The variable a is assigned with 2, and b with 1. The swapping of a and b has been performed.

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 😊

--

--