In recent years, deconstructed food has become popular among gourmets, in which a chef breaks down a dish into core ideas (deconstruction) and reconstructs it from its basic elements (reconstruction). What does this have to do with JavaScript? It also happens to support deconstruction and reconstruction of arrays and objects. Until the release of ECMAScript 6 (ES6), the decomposition part of the equation was much more difficult than the reconstruction, requiring a few lines of code. Now, the ability to deconstruct an array or object in a single line of code offers a wealth of coding possibilities. In this web development tutorial of his, today we’ll focus on object decomposition. In the next article, we’ll focus on compound (object and array) decomposition and its more advanced usage.
Want to learn web development in an online course format? Check out our list of the best HTML and web development courses.
Basics of deconstructing JavaScript
The Advanced TypeScript/ES6 Array Features article touched on Array destructuring and compared the new ES6 syntax to that of previous versions of JavaScript (JS). As an example, I assigned the elements of the 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;
That JavaScript tutorial defined destructuring as a feature of EcmaScript 2015 and Typescript that allows the structure of an entity to be split. While that definition was sufficient in the context of the subject at hand, it omitted several other points about decomposition, such as:
- It can be applied to complex structures (i.e. arrays or objects).
- Can be used for both variable assignment and/or variable declaration.
- It supports nested structured syntax to handle nested structures.
As it applies to objects, let’s cover each of these points in turn.
Example of deconstructing an object in JavaScript
The code snippet above is an example of array partitioning on variable assignment. Since JS objects store their attributes as associative arrays, you can also put object literals on the left side of assignment expressions that deconstruct objects.
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 following snippet shows how to use object decomposition to assign new values to local variables. Note that you must use a pair of parentheses (()) in an assignment expression. Otherwise, an error is thrown because the split object literal is scoped as a block statement and a block cannot appear to the left 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 and deconstructing default values in JS
Destructuring assignment is very flexible and allows assigning variables that do not correspond to any key in the unstructured object. If you do, JS will create the variable and assign it a value without issue. undefinedOtherwise you can assign the default value yourself like this:
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
Renaming Variables in JavaScript
You probably already thought that assigning variables with destructuring is a very powerful thing. Well, it gets even better. Web developers are not limited to variables with the same name as the corresponding object key.A programmer can assign to another 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}.`);
Exploding Nested Objects in JavaScript
As you may have noticed, objects can themselves contain other objects. So it makes sense that child objects can be unstructured as well. Here’s an example showing how to do this:
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 Exploding ES6 Objects
In this web development tutorial, you learned how to deconstruct objects using ES6 syntax. In the next article, we’ll focus on compound (object and array) decomposition and its more advanced usage.
While you wait, why not check out today’s code snippet demos? If you want, you can play with them.
Learn more about JavaScript programming tutorials and software development guides.