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
-
Creating Interactive Accordions using jQuery
Accordions are useful interface elements that, when clicked, will expand or condense the information on a web page. In this article, I will provide examples on how to create accordions and nested accordions using jQuery, and explain when you might want to use accordions.
-
CodePen Challenge: Take on Me
This week, our color palette comes from the video for "Take on Me" by a-ha from 1985. The absence of color is a big part of the video but the crossover moments between the comic book world and the real world are filled with moody pastels.
-
ACF Relationship Field Prev/Next Buttons
Looking to create custom previous and next buttons from ACF's Relationship field with the full code snippet provided? Then you've come to the right place!
-
Security, Hackers, WordPress, and You
WordPress is currently powering 29% of all websites, making it the most popular Content Management System going. As a result, hackers are constantly looking for new ways to get around WordPress’ security so they can hack as many sites as possible.