Arrays and Objects often contain a bunch of data, and there’s always a constant need to extract data from these two data grouping methods. it could be nerve-wracking to extract data from an array using the bracket notation, or from an object using the dot or bracket notation. Or sometimes passing a long chain of properties in a javascript function. Here is where destructuring come to your rescue. Destructuring does mean to destroy rather it is just a syntax used in javascript to assign values to a unique variable. In this article, you will learn how to destructure values in javascript.
Let's get started.
What is destructuring in javascript?
Destructuring is a javascript syntax that makes it possible to assign values extracted from an object, an array or long-chain properties of a function into a distinct variable. Destructuring is a feature introduced into ECMAScript 6.
Assigning Variable from an Object
The way to assign a variable to an object takes a different syntax from the way a variable is assigned to an array. Let's see an example
var testScore = {
chemistry : 78,
physics : 92,
mathematics : 89,
biology : 70,
programming : 86,
english : 68
}
To access the values of the object, we use dot notation. Like this:
var firstScore = testScore.chemistry
console.log(firstScore)// 78
var lastScore = testScore.english
console.log(lastScore // 68
Instead of going through this method, we can destructure the values in the object like this;
const {chemistry, physics, mathematics, biology, programming, english } = testScore
//This will create variables for the 6 subjects from the testScore. Let’s test for the value of a subject.
console.log(physics) // 92
You can also destructure this by storing the scores of the subjects into another variable. Take a look at the step below.
const {chemistry : a, physics : b, mathematics : c, programming : d, english : e} = testScore;
console.log(c); // 89
Assigning variables from nested objects
A nested object is an object inside another object. To destructure a nested object, you can assign a variable from a nested object. Let's take for example;
const testScores = {
higherScores: {physics : 92, mathematics : 89, programming : 86},
lowestScores : {chemistry : 78, biology : 70, English : 68}
};
const {higherScores : {physics : a, mathematics : b, programming : c}}= testScores
console.log(b) // 89.
what we did above is that we assign the value of each subject to the variables a, b, and c respectively. So instead of accessing the nested object property using multiple dot notation, like this:
result = testScores.higherScores.mathematics;
console.log(result); // 89
we just pass the destructured variable ‘b’ and we get our value of 89. This makes assigning values much easier.
Default Value in object
When destructuring an object, you can assign default values to a variable. If a property is initially not in the object, you can create a variable and assign a default value to it. Let’s talk a look at an example
var testScore = {
chemistry : 78,
physics : 92,
mathematics : 89,
biology : 70,
programming : 86,
english : 68
}
//To access the object property
const {chemistry, physics, mathematics, biology, elective = 'history' } = testScore
console.log(biology); // 70
console.log(elective); // history
In this example, the default value “history” was assigned to elective while destructuring.
Rest operator in an Object.
You can use rest syntax to access rest elements in an object. The rest operator comes at the end and allows you to get the remaining properties of an object. The syntax is an ellipsis “ … “ then the name of the array created. The name "rest" that appears after the three dots (ellipsis) is optional. You can use another name after the three dots.
Syntax: (...rest)
Let’s take a look at an example;
var testScore = {
chemistry : 78,
physics : 92,
mathematics : 89,
biology : 70,
programming : 86,
english : 68
}
//To access the object property we have:
const { chemistry : a, ...others} = testScore;
console.log(a); // 78
console.log(others) // physics : 92, Mathematics : 89, biology : 70, programming : 86, English : 68
Assigning a variable from an Array
Just as you can destructure the values for an object, you can do the same for an array, let's look at an example of that.
const subjects = [ "chemistry", "physics", "mathematics", "programming", "biology", "english"];
//Ordinarily, you can index 2 in the subject array by bracket notation
result = subjects[2];
console.log(result); // mathematics.
But to destructure we have:
const [q, r] = [ "chemistry", "physics", "mathematics", "programming", "biology", "english"];
console.log(q, r); // chemistry, physics
//This will give you the first two subjects in the array when you console.log(q, r).
//You can also do;
const [q, r] = subjects;
console.log(q, r); // chemistry, physics
Skipping index with comma
You can access another index in the subject array by adding a comma to reach the desired index. Let's take a look at this by adding two more commas to q in when destructuring
const subjects = [ "chemistry", "physics", "mathematics", "programming", "biology", "english"];
const [q,,, r] = subjects ;
console.log(q, r);// chemistry, programming.
As you can see, we skipped indexes 1 and 2 to reach index 3 which is programming.
Rest Operator in an Array
Just as in an object, you can use the rest operator to extract the other elements of an array. The rest operator just requires you to put an ellipsis (three dots) before rest.
Syntax: (...rest)
Let's take a look at it this example:
const [q, r, ...rest] = [ "chemistry", "physics", "mathematics", "programming", "biology", "english"];
console.log(q, r) // chemistry, physics.
console.log(rest) // mathematics, programming, biology, english
Note: the rest variable only works strictly with the last elements in the array.
Swapping a value in an array
In an array, you can swap a value by switching places. To do this, you will need a third variable. Take, for example, you hold two bottles of Coca-Cola and Pepsi each on your left and right hands. If you are to swap the two bottles you will need a third hand (in this case, someone else) to hold one for you, pass the other on either your left or right and retrieve the back from the third. Let's take a look at how to do this in a few lines of cold.
let arr = ["chemistry", "physics"];
let arr1 = ["mathematics", "programming"];
console.log(arr) // chemistry. physics
console.log(arr1) // mathematics, programming
let newArr = arr1; //passing the values “mathematics, programming” to the new array ( our third hand)
console.log(newArr) // mathematics, programming
arr1 = arr // passing the value of arr to arr1 (from either left hand to the right hand)
arr = newArr; // retrieving the values mathematics, programming from the new array (our third hand) back to either empty hand.
console.log(arr1) // chemistry. physics
console.log(arr) // mathematics, programming
But using destructuring, we can do this without the need for the third hand. Let’s see how to do this;
const array = ["chemistry", "physics", "mathematics"];
let [arr, arr1, arr2] = array;
console.log(arr) // chemistry
console.log(arr1) // physics
[arr, arr1] = [arr1, arr]; // swapping the value using restructuring
console.log(arr); //physics
console.log(arr1) // chemistry
Default Value in an array
When writing your code, you may be confused about what value you are assigning, if that value returns undefined, you may need to use the default value to track it. Destructuring makes this easy to do. Let’s look at an example
const array = ["chemistry", "physics", "mathematics", "programming"];
const [arr, arr1, arr2, arr3, arr4] = array;
console.log(arr) // chemistry
console.log(arr1) // physics
console.log(arr2) // mathematics
console.log(arr3) // programming
console.log(arr4) // undefined
//To assign a default arr4 we use restructuring like this
const array = [ "chemistry", "physics", "mathematics", "programming"];
const [arr, arr1, arr2, arr3, arr4='biology'] = array;
console.log(arr4) // “biology”
Take away
- 1. Destructuring helps you assign a variable to some values and let you pass the variable easily to anywhere where the values assigned to it are needed.
- 2. Destructuring allows you to create a default value to access an unsure element
- 3. You can easily swap array values using destructuring without having to create the third variable.
- 4. You can use the rest operator to access other properties of an object or array.
- 5. Skipping the index in an array can be easily done using destructuring.
Conclusion
In this article, you’ve learned how to do destructuring in objects, and arrays and how to pass objects as a parameter in a function. It is worth noting that aside from the fact that destructuring help you write clean and easy-to-read codes, when you master the concept of destructuring, it will come in handy when dealing with a complex object or array and also while working with React props, you will find it very useful. You can learn more about destructuring in javascript here destructuring in javascript.
Wow! I am glad you read to the end, I hope you’ve learned something useful from this article. If you like what you’ve just read, you could share it with your friends, leave a comment or react to this article by tapping on every emoji at the right corner of this page.
Before you go, let’s connect on