Write concise code using  Destructuring Assignment

Write concise code using Destructuring Assignment

Hello World ๐Ÿ‘‹, Akwaaba, the destructuring assignment is a very useful JavaScript feature that enables you extract values from arrays, or properties from objects and store the values in variables. The destructuring assignment when mastered empowers developers to write more concise, clean and and readable code. In this post, we take a look at how to use the destructuring assignment in JavaScript. Let's roll ๐Ÿš€

Destructuring explained in simple terms

Destructuring means to break down a complex structure into simpler parts

With the syntax of destructuring, you can extract smaller fragments from objects and arrays which can then be assigned to declared variables.

What is Destructuring Assignment?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Why the need for destructuring ?

Oftentimes, when we pass an array or object to a function, we may not need the whole array or object but will only be interested in the individual properties or items. Destructuring assignment makes it possible to take out the individual item or property, assign it to a variable and pass it to the function as it is more convenient.

Destructuring assignment is useful because it allows you to assign properties of an object or items in an array to a variable and later use that variable. We can have both Object destructuring and Array destructuring, in this post, we will focus on Array destructuring

Below, we take a look at Array Destructuring

Array Destructuring

Here, we take a look at how an array is destructured into variables. Let's take a scenario where we have an array of capital cities, and our task is to assign the individual items into variables. Let' see how we can achieve that using the traditional method, and later using destructuring assignment

Traditional method of assigning array items to variables

/* define array of capitals  */
let capitalCities = ["Accra", "Lagos", "Nairobi"];
/* assign the individual items into variables */
let citi1= capitalCities[0];
let citi2 = capitalCities[1];
let citi3 = capitalCities[2];
/*Now we have unpack the array items into distinct variables */
console.log(citi1) /*Accra */
console.log(citi2) /*Lagos */
console.log(citi3) /* Nairobi */

With the code above, we needed to assign each individual array items into variables spanning three lines of code. Can this be more concise using the destructuring assignment ? Let's find out

Destructuring Assignment

With this method , we define the array we want to unpack their items from on the right side of the expression then on the left side we define the variables we want to store these items into. Simple, right ? Check the syntax below ๐Ÿ‘‡

Syntax

 let [firstElem, secondElem, thirdElem]  = array    ๐Ÿ˜ฒ
/*the left-hand side of destructuring assignment is for defining what values are required to unpack from sourced variable. */
/* When destructuring an array, we use their index or position in an assignment. 
This will set firstElem = array[0] 
 sets secondElem = array[1] and 
 sets thirdElem = array[2]
*/

console.log(firstElem)  /*This will give you the value of the first item in the array */
console.log(secondElem) /*This will give you the value of the second item in the array etc */

Now that you know the syntax of the destructuring assignment, let's destructure a capitalCities array

/* define array of capitals  */
let capitalCities = ["Accra", "Lagos", "Nairobi"];
/* unpack the elements in the array and assign the individual items into variables */
let [citi1, citi2, citi3] = capitalCities;    ๐Ÿ˜ฒ
 /* Destructuring above is clean, concise and much readable, just one line of code to unpack the items into variables */
console.log(citi1, citi2, citi3) /* Accra, Lagos, Nairobi */

Basically, what we have done is to copy items into variables and later use those variables. With the destructuring above, we can now work with the distinct variables, instead of the whole array

Ignoring elements using commas

Array destructuring also helps us to get rid of unwanted elements by using commas ,.

In the code below, we have an array of fruits, and our task is to get only first and third fruit in the array. Since we don't need all the array elements, we can destructure the array and take out only the elements we need. Let's see how that can be done ๐Ÿ’ช

/* array of fruits */
let fruits = ["Banana", "Orange", "Pineapple", "Apples", "Mangoes"]

/*unpack the array items and get only the first and third fruits */
let [firstFruit, , thirdFruit] = fruits;    ๐Ÿ˜ฒ
console.log(firstFruit) /* Banana * /
console.log(thirdFruit) /* Pineapple */

In the code above, the first element is assigned to the the variable firstFruit and the third element is assigned to the variable thirdFruit. The , and space in the left side of the assignment after the firstFruit ensures the second element is ignored or skipped ( not assigned to any variable). During destructuring, you have to leave spaces for unwanted elements . The elements you want to skip should be separated by comma , a space and then , ๐Ÿ’ฅ

Take note, any other elements that was not assigned to a variable will also be skipped or ignored, so the fourth and fifth element will be ignored as well.

Array Destructuring and rest operator

Usually, if the array is longer than the variables at the left, the "extra" elements are omitted. Eg. If you have 2 sourced variables, and 5 array items, the remaining three array items will not be unpack into any variable. By using the rest operator, ... in an array destructuring, you can put all the remaining elements of an array into a new arrray.

In the code below, let's assume, we only want the first and second element of the array and the rest should be ignored.

//define the array 
let fruits = ["Banana", "Orange", "Pineapple", "Apples", "Mangoes"]

//unpack the array items and get only the first and second fruits
let [firstFruit,secondFruit, ...rest] = fruits;
console.log(firstFruit) /*Banana */
console.log(secondFruit) /*Orange */
console.log(rest) /* ["Pineapple", "Apples", "Mangoes"]*/

You can use any other variable apart from rest, you should ensure it has ... before it and it goes to the last destructuring assignment.

Setting Default Values

If an array is shorter than the list of variables on the left, those absent values are considered undefined. You can however, set a default value to a variable. In the code below, we have an array of name, and we want to set the middle name to a default value. Let's see how that can be done

let [fullName, middleName= "unknown"] = ["Emmanuel Kumah"];
console.log(fullName) /*Emmanuel Kumah */
/*Assign middleName variable to a default value "unknown" */
console.log(middleName) /*unknown */

With the above, the first element of the array will be stored in the fullName variable and we are done. We can now set the middleName variable to a default value, in this case, we set it to unknown. To set the default value of a variable, we can provide it using =

Swapping Values

The value of two variables can be swapped using destructuring assignment

let admin = "Emma";
let guest= "Joe";
/* Let's swap the values, make guest="Emma" and admin="Joe" */
 [guest, admin]  = [admin, guest];
 console.log(guest) /* Emma */
 console.log(admin) /* Joe */

Parsing returned array from functions

Since it is possible to return an array from a function, the returned value can be parsed in a single line using destructuring

The code below defines a function getArray which outputs an array of countries, because the returned value is an array of countries, we can simply call the function getArray() and assign it to variables on the left side of the expression. Take a look

function getArray(){
    return ["Ghana", "Nigeria"]
}
console.log(getArray()) /* ["Ghana", "Nigeria"] */
// use destructuring assignment  to parse the returned values 
let [firstCountry, secondCountry] = getArray();  ๐Ÿ˜ฒ
console.log(firstCountry) /* Ghana */
console.log(secondCountry) /*Nigeria */

Summary

  • Destructuring deals with taking a complex structure and breaking it into smaller parts, these smaller parts can then be assigned to variables for easy usage.
  • Array destructuring is simple how we assign array elements to variables in a more concise way.

  • The full array syntax is let [item1 = default, item2, ...rest] = array

Using destructuring assignment helps you remove some elements from an array or object and assign it a distinct variable making your code very concise, clean and readable.

Have you learnt something useful, is there something you need to bring to my attention ? Would love to read your comments ๐Ÿ’ญ In my next post, we delve further on how to use Object destructuring see you soon. Me daa se

PS: Akwaaba and Me daa se are Ghanaian ๐Ÿ‡ฌ๐Ÿ‡ญ dialect meaning, Welcome and Thank you respectively โค๏ธ

Writing with love from ๐Ÿ‡ฌ๐Ÿ‡ญ