JavaScript ES6: The Basics of Destructuring
The Basics and Destructuring Objects
Destructuring is one of the most common and important features of JavaScript ES6. It allows us to extract data from arrays and objects, and assign that data into their own variables.
To show how destructuring can change the way you write code, I will go over a common scenario. In the ES5 code below we have a basic object that we are pulling data out of.
// ES5
var book = {
title: 'Harry Potter',
author: 'J.K. Rowling'
};
var title = book.title; // Harry Potter
var author = book.author; // J.K. Rowling
We are pulling each of the object’s properties out into separate variables. This works but it’s very repetitive. The book variable is being written out three times and each property name is being written out twice.
With Destructuring, we can shorten down to reduce the characters used.
const { title } = book; // Harry Potter
const { author } = book; // J.K. Rowling
Don’t be alarmed, the curly braces are supposed to be on the other side of the equals sign! Nope, a new object is not being created. The curly braces on the other side of the equals sign means we are creating a new variable that matches a property of the same name from an object.
So with const { title } = book; we are creating a new variable called title, which is getting its value from the property also called title from the book object. To break it down;
const { variable name and property of the same name } = existing object;
With Destructuring we can even go a step further to combine multiple variables on a single line!
const { title, author } = book;
console.log(title); // Harry Potter
console.log(author); // J.K. Rowling
“Does the variable name have to match up with the property name?”, I hear you cry.
Yes, yes it does. From our book object we cannot do { customTitle, author } = book; as customTitle does not match up with title in the book object.
“But customTitle does not exist in book, what happens when we reference a property that does not exist?”, I hear you cry a second time.
The variable customTitle will simply return as undefined so there is no need to worry about an error being thrown.
Destructuring in Function Arguments
Destructuring can also be used on arguments, allowing us to pull properties off objects that are passed to functions.
In the example below, we have a small function that summarises the book’s details.
// ES5
var book = {
title: 'Harry Potter',
author: 'J.K. Rowling',
price: '$15'
};
function bookSummary(book) {
return `${book.title} is written by ${book.author} and costs ${book.price}`;
}
bookSummary(book); // Harry Potter is written by J.K. Rowling and costs $15
It does the job as expected but there is a lot of repetition going on with the book variable name in the function.
// ES6
function bookSummary({ title, author, price }) {
return `${title} is written by ${author} and costs ${price}`;
}
bookSummary(book); // Harry Potter is written by J.K. Rowling and costs $15
When destructuring in an argument we can pass in the property names instead of using the variable name book. Doing so allows us to remove references to book when returning the function.
Destructuring Arrays
Now that we are familiar with destructuring objects, let’s have a look at how destructuring works with arrays. Destructuring an array allows us to pull from individual elements of the array.
In the example below, we have a simple array with each individual element representing an animal.
const animals = [
'Cat',
'Dog',
'Mouse'
];
In ES5, if we wanted to access one of these elements we would need to do this;
const firstAnimal = animals[0]; // Cat
const secondAnimal = animals[1]; // Dog
const thirdAnimal = animals[2]; // Mouse
There’s nothing wrong with the above code. It works but it’s repetitive.
Destructuring the array will allow us to clean up the repetition and reduce the amount of code we need to write. Similar to how we destructure an object, with an array we’ll be able to access an element in the array and create a variable for that element in one go!
const [ first, second, third ] = animals;
console.log(first); // Cat
console.log(second); // Dog
console.log(third); // Mouse
Similar to how an object uses curly braces, we can place square braces on the opposite side of the equals sign which will create a variable and access the element in the array. So we use {} to destructure an object’s property and use [] to destructure elements in an array.
“What happens if we reach out of bounds of the array?! Something bad?!”.
Nope! If we create a variable out of an array element that does not exist then it won’t throw an error, it will just return as undefined.
const animals = [
'Cat',
'Dog',
'Mouse'
];
const [ first, second, third, fourth ] = animals;
console.log(first); // Cat
console.log(second); // Dog
console.log(third); // Mouse
console.log(fourth); // Undefined
To wrap things up with array, we can also use destructuring alongside the rest operator. Using our animals array, we can target the first element in the array and then use the rest operator to access the remaining elements in the array.
const animals = [
'Cat',
'Dog',
'Mouse'
];
const [ first, ...rest ] = animals;
console.log(first); // Cat
console.log(rest); // [“Dog”, “Mouse”]
That covers the basics on how to destructure objects, function arguments and arrays. If you feel you have the basics down then there are more advanced uses for destructuring that you can get your teeth stuck in to, such as destructuring objects and arrays at the same time, and destructuring arrays nested in other arrays.
Continue Reading
-
CodePen Challenge: Image Hovers
This week's challenge prompt was to design a hover effect for an image. I created a simple effect that will jiggle the jelly when it is moused over!
-
CodePen Challenge: Hero
The goal here was to create a hero with at least one image. I decided to demonstrate how an image overlay can improve text readability. To show how well this works across a wide array of images, a reload button is included which keeps reloading new images from picsum!
-
JavaScript ES6: The map() Helper
The map() helper is used when we want to modify a list of data. When map() is finished running, it creates and populates a new array with the results. Let's see how it works!
-
Next-gen Images: Page Speed’s New Best Friend
Converting your images to a next-gen image format, like WebP, is one of the best ways to improve the user’s experience and page speed on your website.