JavaScript Destructing Assignment

Introduction 

 
In this blog post, we are going to tackle the destructuring assignment that makes developer's lives easier. To make it simple, destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that resembles the creation of an array or object. Just to give a bit of background for new JS developers, in the earlier years of JS the need to fetch information from objects and arrays could result in a lot of duplicate code just to get the data needed especially for the large and complex data structure. That's why destructuring for objects and arrays were added as part of JavaScript/ES6. 
 
Lastly, there are two kinds of destructuring assignment expressions, the array and object assignment. We are going to see each of them in action but don't forget the destructured parameters which are helpful when passing function arguments.
 

Array Destructuring Assignment

 
Before diving in more examples, let's try to see an example before ES6. 
  1. var fruits = ["apple""banana""watermelon"];  
  2.   
  3. var apple = fruits[0];  
  4. var banana = fruits[1];  
  5. var waterMelon = fruits[2];  
  6.   
  7. console.log(apple, banana, waterMelon); //output apple banana watermelon  
As you can see in the example above, it actually extracts the values of the array and assigns them to the apple, banana, waterMelon variables respectively.
 
Today, with the use of ES6, we can do this with a one-line statement using the array destructuring assignment. Let's try to convert to the above example to the ES6 way. 
  1. let fruits = ["apple""banana""watermelon"];  
  2.   
  3. let [apple, banana, waterMelon] = fruits;  
  4.   
  5. console.log(apple, banana, waterMelon); //output apple banana watermelon  
Now, isn't that nice? As you can see, the [apple, banana, waterMelon] is the array destructuring expression, similar to an array literal expression. Moreover, the left-hand side of the array destructuring expression is where we place the variables to which we want to assign the array values. While, on the right-hand side, where we place an array whose values we want to extract.  
 
One great thing to mention about array destructuring, it makes easier to swap the values of two variables. It is common in most JS projects to have value swapping in some form or kind. Let us see the ES6  example of swapping values. 
  1. let num1 =1, num2 =2;  
  2.   
  3. console.log(num1, num2); //output 1 2  
  4.   
  5. [num1, num2] = [num2, num1];  
  6.   
  7. console.log(num1, num2); //output 2 1  
Great! We have now an idea about array restructuring. Let's move on with more examples. 
  1. let basketballPlayers = [  
  2.                         {firstName : "James", lastName : "Harden", team : "HOU" },  
  3.                         {firstName : "Bradley", lastName : "Beal", team : "WAS" },  
  4.                         {firstName : "Giannis", lastName : "Antetokounmpo", team : "MIL" },  
  5.                         {firstName : "Trae", lastName : "Young", team : "ATL" },  
  6.                         {firstName : "Damian", lastName : "Lilard", team : "POR" },  
  7.                         "Mercedes G550 4x4²",  
  8.                         "2018 Bentley Continental GT",   
  9.                         "Range Rover"  
  10.                         ];   
From the array basketballPlayers we are going to extract different values that we want to learn more about array destructuring.
 

Ignoring values

 
We can use commas within the array destructuring expression to omit values that we are not interested in. See an example below, where we only want the first, second, and fourth player within the array. 
  1. let [firstPlayer, secondPlayer, ,fourthPlayer] = basketballPlayers;  
  2.   
  3. console.log(firstPlayer, secondPlayer, fourthPlayer);   
  4. //--start of output--  
  5. //{ firstName: 'James', lastName: 'Harden', team: 'HOU' }   
  6. //{ firstName: 'Bradley', lastName: 'Beal', team: 'WAS' }   
  7. //{ firstName: 'Trae', lastName: 'Young', team: 'ATL' }  
  8. //--end of output--  

Rest parameter

 
If you aren't familiar with the concepts of rest parameter yet, please see my previous post on C# corner about spread operators and rest parameters.
  1. let [,,,, fifthPlayer, ...favoriteCars]  = basketballPlayers;  
  2.   
  3. console.log(fifthPlayer, favoriteCars);  
  4. //--start of output  
  5. //{ firstName: 'Damian', lastName: 'Lilard', team: 'POR' }   
  6. //[ 'Mercedes G550 4x4²', '2018 Bentley Continental GT', 'Range Rover' ]  
  7. //--end of output  
Within the example above, it shows that we only care for the fifth player within the array collection and the remaining items within the basketballPlayers array with the usage of rest parameter with the variable favoriteCars respectively.
 

Default Values

 
With the usage of array destructuring expression, you can also specify default values for any position in the array. See the examples below:
  1. let fruits = ["apple""banana"];  
  2.   
  3. let [apple, banana, waterMelon = "watermelon", avocado = "avocado"] = fruits;  
  4.   
  5. console.log(apple, banana, waterMelon, avocado); 
  6. //output: apple banana watermelon avocado  
  1. let ballBrands = ["spalding""mikasa", undefined];  
  2.   
  3. let [spalding, mikasa, wilson ="wilson"] = ballBrands;  
  4.   
  5. console.log(spalding, mikasa, wilson);
  6. //output: spalding mikasa wilson  

Object Destructuring Assignment

Again, before diving into more examples, let's try to see an example before ES6.
  1. var basketBallPlayer =    
  2. {firstName : "James", lastName : "Harden", team : "HOU" };  
  3.   
  4. var firstName = basketBallPlayer.firstName;  
  5. var lastName = basketBallPlayer.lastName;  
  6. var team = basketBallPlayer.team;  
  7.   
  8. console.log(firstName, lastName, team);  
  9. //output James Harden HOU  
Today, with the use of ES6 we can do this with one line statement using the object destructuring assignment. Let's try to convert to the above example to the ES6 way.
  1. let basketBallPlayer =    
  2. {firstName : "James", lastName : "Harden", team : "HOU" };  
  3.   
  4. let { firstName ,lastName, team } = basketBallPlayer;  
  5.   
  6. console.log(firstName, lastName, team);  
  7. //output James Harden HOU  
Let's create even more examples to explore with object destructuring assignments. 
  1. let basketBallPlayer = {  
  2.     firstName: "James",  
  3.     lastName: "Harden",  
  4.     age: 30,  
  5.     jerseyNumber: 13,  
  6.     experience: 10,   
  7.     avgStats: {  
  8.         points: 34.4,  
  9.         reb: 6.4,  
  10.         ast: 7.4,  
  11.         year: {  
  12.             year: '2019-20',  
  13.             team: 'HOU',  
  14.             points: 34.4  
  15.         }  
  16.     }  
  17. }  
From the object basketballPlayer we are going to extract different values that we want to learn more about object destructuring.
 

Default Values

 
With the usage of object destructuring expression, you can also specify default values for any property name that doesn't exist on the object. See the examples below.
  1. let { age, nickname = "n/a" } = basketBallPlayer; //default values for the variables  
  2.   
  3. console.log(age, nickname); //output 30 n/a  

Nested Object Destructuring

 
We can navigate into a nested object structure to retrieve just the information we want. We can use the curly braces {} to indicate that the pattern should descend into a certain property we want to retrieve. See the example below. 
  1. let { jerseyNumber, avgStats: {year}} = basketBallPlayer; //destructuring nested objects  
  2.   
  3. console.log(jerseyNumber, avgStats.year);   
  4. //output 13 { year: '2019-20', team: 'HOU', points: 34.4 }  

Assigning Values to Different Local Variable Names

 
Object destructuring assignment works well with object property name as the local variable name. However, what if you don't? JS/ES6 has an extended syntax for this which allows you to assign to a local variable with a different name. See the example below:
  1. let { firstName: customFirstName,   
  2.       lastName: customLastName,   
  3.       experience: professionalExp} = basketBallPlayer;  
  4. //output James Harden 10  

Destructuring Assignments as Parameter

 
In this last, section we have a good grasp about array and object destructuring assignment. So, let's go straight ahead and show examples of how to use this technique as a function parameter. 
  1. function myFuncObj({firstName = 'n/a', age = 1, profession = "Basketball Player"}= {})  
  2. {  
  3.     console.log(firstName, age, profession);  
  4. }  
  5.   
  6. myFuncObj();   
  7. //output: n/a 1 Basketball Player  
  8.   
  9. myFuncObj({firstName : "James", age : 33, team : "HOU"});  
  10. //James 33 Basketball Player  
  11.   
  12.   
  13. function myFuncArary([favoriteFruit ='',  favoriteFood ='any food', favoriteSong = 'n/a'] =[]){  
  14.     console.log(favoriteFruit, favoriteFood, favoriteSong);  
  15. }  
  16.   
  17. myFuncArary();   
  18. //output any food n/a  
  19.   
  20. myFuncArary(["apple""With a Smile""Fried Chicken"]);  
  21. //output apple Fried Chicken With a Smile  
  22.   
  23. myFuncArary(["apple"]);   
  24. //output apple any food n/a  

Summary

 
In this blog post, we have discussed destructuring assignment syntax for both arrays and objects added to JavaScript/ES6. I hope you have enjoyed this blog post, as much as I have enjoyed writing and coding the examples. Until next time, happy programming.