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.
- var fruits = ["apple", "banana", "watermelon"];
-
- var apple = fruits[0];
- var banana = fruits[1];
- var waterMelon = fruits[2];
-
- console.log(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.
- let fruits = ["apple", "banana", "watermelon"];
-
- let [apple, banana, waterMelon] = fruits;
-
- console.log(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.
- let num1 =1, num2 =2;
-
- console.log(num1, num2);
-
- [num1, num2] = [num2, num1];
-
- console.log(num1, num2);
Great! We have now an idea about array restructuring. Let's move on with more examples.
- let basketballPlayers = [
- {firstName : "James", lastName : "Harden", team : "HOU" },
- {firstName : "Bradley", lastName : "Beal", team : "WAS" },
- {firstName : "Giannis", lastName : "Antetokounmpo", team : "MIL" },
- {firstName : "Trae", lastName : "Young", team : "ATL" },
- {firstName : "Damian", lastName : "Lilard", team : "POR" },
- "Mercedes G550 4x4²",
- "2018 Bentley Continental GT",
- "Range Rover"
- ];
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.
- let [firstPlayer, secondPlayer, ,fourthPlayer] = basketballPlayers;
-
- console.log(firstPlayer, secondPlayer, fourthPlayer);
-
-
-
-
-
Rest parameter
- let [,,,, fifthPlayer, ...favoriteCars] = basketballPlayers;
-
- console.log(fifthPlayer, favoriteCars);
-
-
-
-
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:
- let fruits = ["apple", "banana"];
-
- let [apple, banana, waterMelon = "watermelon", avocado = "avocado"] = fruits;
-
- console.log(apple, banana, waterMelon, avocado);
-
- let ballBrands = ["spalding", "mikasa", undefined];
-
- let [spalding, mikasa, wilson ="wilson"] = ballBrands;
-
- console.log(spalding, mikasa, wilson);
-
Object Destructuring Assignment
Again, before diving into more examples, let's try to see an example before ES6.
- var basketBallPlayer =
- {firstName : "James", lastName : "Harden", team : "HOU" };
-
- var firstName = basketBallPlayer.firstName;
- var lastName = basketBallPlayer.lastName;
- var team = basketBallPlayer.team;
-
- console.log(firstName, lastName, team);
-
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.
- let basketBallPlayer =
- {firstName : "James", lastName : "Harden", team : "HOU" };
-
- let { firstName ,lastName, team } = basketBallPlayer;
-
- console.log(firstName, lastName, team);
-
Let's create even more examples to explore with object destructuring assignments.
- let basketBallPlayer = {
- firstName: "James",
- lastName: "Harden",
- age: 30,
- jerseyNumber: 13,
- experience: 10,
- avgStats: {
- points: 34.4,
- reb: 6.4,
- ast: 7.4,
- year: {
- year: '2019-20',
- team: 'HOU',
- points: 34.4
- }
- }
- }
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.
- let { age, nickname = "n/a" } = basketBallPlayer;
-
- console.log(age, nickname);
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.
- let { jerseyNumber, avgStats: {year}} = basketBallPlayer;
-
- console.log(jerseyNumber, avgStats.year);
-
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:
- let { firstName: customFirstName,
- lastName: customLastName,
- experience: professionalExp} = basketBallPlayer;
-
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.
- function myFuncObj({firstName = 'n/a', age = 1, profession = "Basketball Player"}= {})
- {
- console.log(firstName, age, profession);
- }
-
- myFuncObj();
-
-
- myFuncObj({firstName : "James", age : 33, team : "HOU"});
-
-
-
- function myFuncArary([favoriteFruit ='', favoriteFood ='any food', favoriteSong = 'n/a'] =[]){
- console.log(favoriteFruit, favoriteFood, favoriteSong);
- }
-
- myFuncArary();
-
-
- myFuncArary(["apple", "With a Smile", "Fried Chicken"]);
-
-
- myFuncArary(["apple"]);
-
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.