Friday, August 19, 2022

ES6 Object Destructuring

Angular and JavaScript
In recent years, deconstructed foods have become all the rage among foodies, whereby chefs break down dishes to their core idea (destructuring) and then rebuild them up from their basic components (restructuring). What does this have to do with JavaScript? As it happens, it also supports the destructuring and restructuring of Arrays and Objects. Until the release of ECMAScript 6 (ES6), the destructuring part of the equation was a lot harder to achieve than the restructuring, requiring several lines of code to accomplish. Now, the ability to destructure an Array or Object in one line of code offers a wealth of coding possibilities. In this web development tutorial, we will be concentrating on Object destructuring today; the next article will focus on mixed (Object and Array) destructuring, along with some of its more advanced uses.

Looking to learn web development in an online course format? Check out our listing of some of the best HTML and web development courses.

JavaScript Destructuring Basics

The Advanced TypeScript/ES6 Array Features article touched on Array destructuring and compared the new ES6 syntax with that of previous versions of JavaScript (JS). As an example, we assigned the elements of an array to four separate variables:

// in pre-ES6 Javascript
var ivoryKnightMembers = ['John', 'Rob', 'George', 'Steve'];
var john   = ivoryKnightMembers[0], 
    rob    = ivoryKnightMembers[1],
    George = ivoryKnightMembers[2], 
    Steve  = ivoryKnightMembers[3];

// using ES6 destructuring
let ivoryKnightMembers = ['John', 'Rob', 'George', 'Steve'];
let [john, rob, george, steve] = ivoryKnightMembers;

In that JavaScript tutorial, we defined destructuring as a feature of EcmaScript 2015 and Typescript that allows you to break up the structure of an entity. While that definition sufficed in the context of the subject matter at hand, it omitted a few other points about destructuring, such as:

  • It can be applied to an complex structure (i.e., an array or object).
  • It can be used for both variable assignment and/or variable declaration.
  • It supports nested destructuring syntax to handle nested structures.

So lets cover each of these points in turn as they apply to Objects.

Object Destructuring Examples in JavaScript

The above code snippet is an example of Array destructuring in a variable assignment. Since JS Objects store their attributes as Associative Arrays, we can also place an Object literal on the left-hand side of an assignment expression for object destructuring:

const band = {
    drummer: 'George',
    bassist: 'Steve',
    guitarist: 'Rob',
    vocalist: 'John'
};

// Object Destructuring
const { drummer, bassist, guitarist, vocalist } = band;

// Outputs "George, Steve, Rob, John"
console.log(drummer, bassist, guitarist, vocalist); 

Assigning New Values to Local Variables

The next snippet shows how to use object destructuring to assign new values to local variables. Notice that we have to use a pair of enclosing parentheses (()) in the assignment expression. Otherwise, the destructuring object literal will be scoped as a block statement, which will throw an error because a block cannot appear at the left-hand side of an assignment expression:

// Initialize local variables
let drummer = 'George';
let bassist = 'Steve';
let guitarist = 'Rob';
let vocalist = 'John';

const band = {
    drummer: 'George',
    bassist: 'Steve',
    guitarist: 'Rob',
    vocalist: 'John'
};

// Reassign firstname and lastname using destructuring
// Enclose in a pair of parentheses, since this is an assignment expression
({ drummer, guitarist } = band);

// bassist and vocalist remain unchanged
// Outputs "George, Steve, Rob, John"
console.log(drummer, bassist, guitarist, vocalist);  

Assigning Default Values and Destructuring in JS

Destructuring assignment is very flexible, allowing you to assign variables that do not correspond to any keys on the destructured object. If you do, JS will happily create the variable and assign it a value of undefined. Otherwise, you can assign a default value yourself like so:

const band = {
    drummer: 'George',
    bassist: 'Steve',
    guitarist: 'Rob',
    vocalist: 'John'
};

// Assign default value of 'Allan' to keyboardist if undefined
const { drummer, bassist, guitarist, keyboardist = 'Allan', vocalist } = band;

// List band members using ES6 template literals
// Outputs "Ivory Knight are George, Steve, Rob, Allan, and John"
console.log(`Ivory Knight are ${drummer}, ${bassist}, ${guitarist}, ${keyboardist}, and ${vocalist}.`);

Read: Using JavaScript Variables and Built-in Functions

Changing Variable Names in JavaScript

You are probably already thinking that variable assignment using destructuring is pretty powerful stuff. Well, it gets even better. Web developers are not limited to variables that have the same name as their corresponding object key. Programmers can assign to a different variable name using the syntax [object_key]:[variable_name]. Want to set some default values? You can assign some using the syntax [object_key]:[variable_name] = [default_value]:

const band = {
    drummer: 'George',
    bassist: 'Steve',
    guitarist: 'Rob',
    vocalist: 'John'
};

// Assign default value of 'Allan' to keyboards if undefined
const { drums: drummer, bass: bassist = 'New guy', guitars: guitarist, keyboards = 'Allan', vocals: vocalist } = band;

// List band members using ES6 template literals
// Outputs "Ivory Knight are George, New guy, Rob, Allan, and John"
console.log(`Ivory Knight are ${drums}, ${bass}, ${guitars}, ${keyboards}, and ${vocals}.`);

Nested Object Destructuring in JavaScript

As I am sure you are aware, objects can themselves contain other objects. Therefore, it makes sense that child objects can also be destructured. Here is an example that demonstrates how to do that:

const band = {
    drummer: 'George',
    bassist: 'Steve',
    guitarist: 'Rob',
    vocalist: 'John',
    backupVocals: {
      lowBackups: 'Steve',
      highBackups: 'Rob'
    }
};

// Assign to local variables
const { drummer, bassist, guitarist, vocalist, backupVocals: {lowBackups, midBackups = 'N/A', highBackups} } = band;

// Outputs "Backup vocals performed by Steve, N/A, Rob."
console.log(`Backup vocals performed by ${lowBackups}, ${midBackups}, ${highBackups}.`);

Final Thoughts on ES6 Object Destructuring

In this web development tutorial, we learned how to destructure Objects using ES6 syntax. The next article will focus on mixed (Object and Array) destructuring, along with some of its more advanced uses.

While you’re waiting for that, why not check out the demo of today’s code snippets? You can even play around with them if you like!

Read more JavaScript programming tutorials and software development guides.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Popular Articles

Featured