Destructuring In JavaScript
Make your code terse! Here are some pointers to help you avoid headaches when using large objects in JavaScript.
One of the many convenient features of ECMAScript in recent years is the introduction of destructuring. The destructuring assignment syntax allows developers to extract values and properties from arrays and objects, respectively. This syntax grants us the ability to be terse and illustrate, most of the time, a clearer sense of the data in use. Destructuring should not be confused with destructors in other languages like C++, which is a method that's invoked when an object either falls out of scope or is called on using a keyword like delete
.
Here we have a sample object representing a blog post:
const blogPost = {
id: "2AOYu4N0",
title: "(Highway To The) Danger Zone",
dateTime: "1986-05-16T20:45:00-0400",
body: "A lot of text ... all up in here!",
categories: [
"Tome Crews",
"Keh-knee Floggins",
"Eight-Tees",
],
};
To access the categories, this is how we would access them traditionally:
var tc = blogPost.categories[0];
var kf = blogPost.categories[1];
var et = blogPost.categories[2];
// or this way ... if you enjoy torturing co-workers
var cat = blogPost.categories;
var tc = cat[0];
var kf = cat[1];
var et = cat[2];
... but with destructuring, we can clearly convey the same in a terse manner:
var { categories } = blogPost;
var [tc, kf, et] = categories;
// ... or in one line ...
var { categories: [tc, kf, et] } = blogPost;
What we're doing here is accessing the categories
property within the blogPost
object and taking the first 3 items in the array (denoted by the []
brackets).