{"id":11736,"date":"2022-07-12T17:32:05","date_gmt":"2022-07-12T17:32:05","guid":{"rendered":"https:\/\/www.htmlgoodies.com\/?p=11736"},"modified":"2022-07-12T17:32:05","modified_gmt":"2022-07-12T17:32:05","slug":"es6-destructuring-javascript","status":"publish","type":"post","link":"https:\/\/www.htmlgoodies.com\/javascript\/es6-destructuring-javascript\/","title":{"rendered":"ES6 Object Destructuring"},"content":{"rendered":"
\nIn 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.<\/p>\n
Looking to learn web development in an online course format? Check out our listing of some of the best HTML and web development courses<\/a>.<\/p>\n The Advanced TypeScript\/ES6 Array Features<\/a> 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:<\/p>\n 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:<\/p>\n So lets cover each of these points in turn as they apply to Objects.<\/p>\n 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:<\/p>\n 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 (()<\/strong>) 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:<\/p>\n 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<\/strong>. Otherwise, you can assign a default value yourself like so:<\/p>\n Read:<\/strong> Using JavaScript Variables and Built-in Functions<\/a><\/p>\n 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 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:<\/p>\n 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.<\/p>\n While you’re waiting for that, why not check out the demo<\/a> of today’s code snippets? You can even play around with them if you like!<\/p>\nJavaScript Destructuring Basics<\/h2>\n
\/\/ in pre-ES6 Javascript\r\nvar ivoryKnightMembers = ['John', 'Rob', 'George', 'Steve'];\r\nvar john = ivoryKnightMembers[0], \r\n rob = ivoryKnightMembers[1],\r\n George = ivoryKnightMembers[2], \r\n Steve = ivoryKnightMembers[3];\r\n\r\n\/\/ using ES6 destructuring\r\nlet ivoryKnightMembers = ['John', 'Rob', 'George', 'Steve'];\r\nlet [john, rob, george, steve] = ivoryKnightMembers;\r\n<\/pre>\n
\n
Object Destructuring Examples in JavaScript<\/h2>\n
const band = {\r\n drummer: 'George',\r\n bassist: 'Steve',\r\n guitarist: 'Rob',\r\n vocalist: 'John'\r\n};\r\n\r\n\/\/ Object Destructuring\r\nconst { drummer, bassist, guitarist, vocalist } = band;\r\n\r\n\/\/ Outputs \"George, Steve, Rob, John\"\r\nconsole.log(drummer, bassist, guitarist, vocalist); \r\n<\/pre>\n
Assigning New Values to Local Variables<\/h3>\n
\/\/ Initialize local variables\r\nlet drummer = 'George';\r\nlet bassist = 'Steve';\r\nlet guitarist = 'Rob';\r\nlet vocalist = 'John';\r\n\r\nconst band = {\r\n drummer: 'George',\r\n bassist: 'Steve',\r\n guitarist: 'Rob',\r\n vocalist: 'John'\r\n};\r\n\r\n\/\/ Reassign firstname and lastname using destructuring\r\n\/\/ Enclose in a pair of parentheses, since this is an assignment expression\r\n({ drummer, guitarist } = band);\r\n\r\n\/\/ bassist and vocalist remain unchanged\r\n\/\/ Outputs \"George, Steve, Rob, John\"\r\nconsole.log(drummer, bassist, guitarist, vocalist); \r\n<\/pre>\n
Assigning Default Values and Destructuring in JS<\/h3>\n
const band = {\r\n drummer: 'George',\r\n bassist: 'Steve',\r\n guitarist: 'Rob',\r\n vocalist: 'John'\r\n};\r\n\r\n\/\/ Assign default value of 'Allan' to keyboardist if undefined\r\nconst { drummer, bassist, guitarist, keyboardist = 'Allan', vocalist } = band;\r\n\r\n\/\/ List band members using ES6 template literals\r\n\/\/ Outputs \"Ivory Knight are George, Steve, Rob, Allan, and John\"\r\nconsole.log(`Ivory Knight are ${drummer}, ${bassist}, ${guitarist}, ${keyboardist}, and ${vocalist}.`);\r\n<\/pre>\n
Changing Variable Names in JavaScript<\/h3>\n
[object_key]:[variable_name]<\/code>. Want to set some default values? You can assign some using the syntax
[object_key]:[variable_name] = [default_value]<\/code>:<\/p>\n
const band = {\r\n drummer: 'George',\r\n bassist: 'Steve',\r\n guitarist: 'Rob',\r\n vocalist: 'John'\r\n};\r\n\r\n\/\/ Assign default value of 'Allan' to keyboards if undefined\r\nconst { drums: drummer, bass: bassist = 'New guy', guitars: guitarist, keyboards = 'Allan', vocals: vocalist } = band;\r\n\r\n\/\/ List band members using ES6 template literals\r\n\/\/ Outputs \"Ivory Knight are George, New guy, Rob, Allan, and John\"\r\nconsole.log(`Ivory Knight are ${drums}, ${bass}, ${guitars}, ${keyboards}, and ${vocals}.`);\r\n<\/pre>\n
Nested Object Destructuring in JavaScript<\/h2>\n
const band = {\r\n drummer: 'George',\r\n bassist: 'Steve',\r\n guitarist: 'Rob',\r\n vocalist: 'John',\r\n backupVocals: {\r\n lowBackups: 'Steve',\r\n highBackups: 'Rob'\r\n }\r\n};\r\n\r\n\/\/ Assign to local variables\r\nconst { drummer, bassist, guitarist, vocalist, backupVocals: {lowBackups, midBackups = 'N\/A', highBackups} } = band;\r\n\r\n\/\/ Outputs \"Backup vocals performed by Steve, N\/A, Rob.\"\r\nconsole.log(`Backup vocals performed by ${lowBackups}, ${midBackups}, ${highBackups}.`);\r\n<\/pre>\n
Final Thoughts on ES6 Object Destructuring<\/h2>\n