Javascript destructuring

Javascript destructuring

Array and Object destructuring

Introduction

Arrays and objects are the most commonly used data types in JavaScript. Hence, mastering their manipulation in an easy way saves you a lot of hustle.

By analogy, this process is like disassembling a complete bicycle into its individual parts and deciding whether to work on them separately or in groups as in the cover photo above.

This article explores how we can extract values from arrays or properties from objects and assign them to separate variables using destructuring assignment syntax, a process known as destructuring.

Prerequisite

Prior basic knowledge of arrays, objects, and their use in Javascript is recommended before reading this article.

The old way of working with arrays and objects

In older versions of JavaScript (before ES6), we used to access and declare array values and object properties as shown below:

i) Arrays

const movies= ["Extraction", "Fast X", "Kandahar"];

let movie1= movies[0];
let movie2= movies[1];
let movie3= movies[2];

console.log(movie1);
//OUTPUT: Extraction
console.log(movie2);
//OUTPUT: Fast X
console.log(movie3);
//OUTPUT: Kandahar

The code above initializes an array called "movies" and assigns values to it. To extract the values from the "movies" array, we use the "let" keyword to declare variables named "movie1," "movie2," and "movie3," and pass in the corresponding array index. Each of these variables stores the value at its respective index in the "movies" array.

ii) Objects

let movies= {
firstmovie: "Extraction",
secondmovie: "Fast X",
thirdmovie: "Kandahar"
};

let movie1= movies.firstmovie;
let movie2= movies.secondmovie;
let movie3= movies.thirdmovie;

console.log(movie1);
//OUTPUT: Extraction
console.log(movie2);
//OUTPUT: Fast X
console.log(movie3);
//OUTPUT: Kandahar

In the provided code, an object named "movies" was declared with properties: firstmovie, secondmovie, and thirdmovie, containing values "Extraction"', "Fast X", and "'Kandahar". To access these values, new variables are declared using "let" and the corresponding property names. Each variable stores the value associated with its respective property name from the object.

The downside of this old way of deconstructing arrays and objects is it leads to code duplication hence the need for destructuring.

Destructuring in arrays and objects

Introduction of destructuring has led to the writing of DRY (Don't Repeat Yourself) code which is more readable, a hack used by top programmers.

Destructuring is also common in javascript frameworks hence the need to understand how it works.

Below, we shall discuss array destructuring and object destructuring.

i) Array destructuring

This can be done through the following methods;

a) Direct assignment of variable names

An example is shown below:

const [movie1, movie2, movie3] = ["Extraction", "Fast X", "Kandahar"];

console.log(movie1);
//OUTPUT: Extraction
console.log(movie2);
//OUTPUT: Fast X
console.log(movie3);
//OUTPUT: Kandahar

When executing the code, movie1 is set to "Extraction," movie2 is set to "Fast X," and movie3 is set to "Kandahar." The order in which they are assigned matters in this method as they are matched respectively to their position.

b) Declarative-Indirect assignment of variable names

An example is shown below;

let movie1, movie2, movie3;
[movie1, movie2, movie3] = ["Extraction", "Fast X", "Kandahar"];

console.log(movie1);
//OUTPUT: Extraction
console.log(movie2);
//OUTPUT: Fast X
console.log(movie3);
//OUTPUT: Kandahar

The code above works the same as the direct assignment of variable names method. The difference is only that here, we first declare variable names and assign them values later. This method is useful in making the variables accessible in the global scope, achieved by creating variable names in the global scope and giving them values in the local scope.

Similarly, the order in which they are assigned matters in this method as they are matched respectively to their position.

c) Use of rest operator

The rest operator (...) is used in cases whereby we only need to extract certain array values grouping the rest into one variable.

An example is shown below:

const [movie1, ...othermovies] = ["Extraction", "Fast X", "Kandahar"];

console.log(movie1);
//OUTPUT: Extraction
console.log(othermovies);
//OUTPUT: ['Fast X', 'Kandahar']

The code above stores the "Extraction" value in the movie1 variable and the othermovies variable stores both "Fast X" and "Kandahar" values in an array.

Note that the rest operator must always be used last in the array, followed by its variable name. Using it in any other position will result in a syntax error.

Additionally, we can extract more than one value and store each in its variable as long as the rest operator is used last. An example is shown below where we have an array with four values.

const [movie1, movie2, ...othermovies] = ["Extraction", "Oppenheimer", "Fast X", "Kandahar"];

console.log(movie1);
//OUTPUT: Extraction
console.log(movie2);
//OUTPUT: Oppenheimer
console.log(othermovies);
//OUTPUT: ['Fast X', 'Kandahar']

d) Targeted values’ extraction

To skip an array value that doesn't need to be stored as a variable, we can use a comma ( ,).

An example is shown below:

const [, , movie3] = ["Extraction", "Fast X", "Kandahar"];

console.log(movie3);
//OUTPUT: Kandahar

The code above executes by using commas as placeholders for the unneeded array values and stores "Kandahar" in the "movie3" variable.

ii) Object destructuring

This can be done through the following methods:

a) Direct assignment of variable names

An example is shown below:

let {movie1, movie2, movie3} ={
movie1: "Extraction",
movie2: "Fast X",
movie3: "Kandahar"
};

console.log(movie1);
//OUTPUT: Extraction
console.log(movie2);
//OUTPUT: Fast X
console.log(movie3);
//OUTPUT: Kandahar

In the code above, we directly declare the object's property names as movie1, movie2, and movie3 and assign a value to each later.

b) Redeclaring property names in predeclared object properties

An example is shown below;

let movies = {
firstmovie: "Extraction",
secondmovie: "Fast X",
thirdmovie: "Kandahar"
};

let { firstmovie: movie1, secondmovie: movie2, thirdmovie: movie3} = movies;

console.log(movie1);
//OUTPUT: Extraction
console.log(movie2);
//OUTPUT: Fast X
console.log(movie3);
//OUTPUT: Kandahar

In the code above, we declare the "movies" object and its properties. Each property has its value. Later on, we assign new property names to replace the existing ones in the "movies" object. Using the old property names in the console.log will result in a syntax error.

c) Use of rest operator

As in arrays, the rest operator (...) is used in cases whereby we only need to extract certain object values and group the rest into one variable.

let {movie1, ...othermovies} = {
movie1: "Extraction", 
movie2: "Fast X", 
movie3: "Kandahar"};

console.log(movie1);
//OUTPUT: Extraction
console.log(othermovies);
//OUTPUT: {movie2: 'Fast X', movie3: 'Kandahar'}

In the code above, an object is created with the properties "movie1" and "othermovies". The "othermovies" property, preceded by the rest operator, stores the remaining property values in an array.

Note that the rest operator must always be used last, followed by its variable name. Using it in any other position will result in a syntax error.

d) Declarative-Indirect assignment of variable names

An example is shown below;

let movie1, movie2, movie3;

({movie1, movie2, movie3 } = {
movie1: "Extraction",
movie2: "Fast X",
movie3: "Kandahar"
});

console.log(movie1);
//OUTPUT: Extraction
console.log(movie2);
//OUTPUT: Fast X
console.log(movie3);
//OUTPUT: Kandahar

In the code above, we declare the variable names. The variable names in the object are assigned properties each with a value. We can then console each individually using the property names.

Note that we enclosed the destructuring code in ( ). This identifies it as an object literal.

Additional notes

In both arrays and objects;

i) Destructuring can be used in functions. This may be done in the function parameters and the set parameter defaults.

ii) Each destructured property can have a default value set. This avoids occurrences of undefined displays on running the code as they are set to the default values.

iii) Destructuring can be used in nested arrays and objects to access values.

Conclusion

Destructuring is considered a best practice to use in accessing array and object values.

***Hope you found this article useful. Thanks for the read, feel free to leave a like and a comment.***👍😁