ARRAY DESTRUCTURING IN JAVASCRIPT

ARRAY DESTRUCTURING IN JAVASCRIPT

Arrays are one of the data structures in Javascript. An array allows us to collect data items into a list. Each data item in an array has an index attached(0-indexed). For example, an array of students offering a course is seen below.

const students = ["Ajay", "Bake", "Fash", "Lola", "Jerry"];
console.log(students[1]);  //Bake

With indexing, we can extract data items from an array. In ES6, another approach was introduced: Assignment Destructuring

Destruction is a Javascript expression that allows you unpack values from arrays, objects into distinct variables. You can extract multiple data items in one line of code and assign them to unique variables. This is much better than doing the repetitive approach to getting each data item.

BASIC ARRAY DESTRUCTURING

To unpack the students array into distinct variables

const[student1, student2, student3] = students;
console.log(student1);  //Ajay
console.log(student2);  //Bake
console.log(student3);  //Fash

SKIPPING DATA ITEMS

Say you want to unpack student2 and student5 into distinct variables, you can use a , to denote each data item you are skipping.

// student1, student3, and student are not needed, so you skip them
const [,student2, , , student5] = students;
console.log(student5); // Jerry

THE REST OF THE ARRAY

Let's assume we have assigned student1 and student2, the rest of the student array is ignored and not assigned to any variable.

With the rest parameter ..., you can assign the rest of the student array to a variable. It returns an array of the remaining data items.

const[student1, student2, ...otherStudents] = students;
console.log(otherStudents); // [ 'Fash', 'Lola', 'Jerry' ]

SETTING DEFAULT VALUES

A variable can be assigned a default value if it has no value from the array to be restructured.

const [student1="Joy", student2] = students;
console.log(student1); // Joy instead of Ajay
console.log(student2); // Bake

In conclusion, array restructuring allows you to extract data items from an array and assign them to unique variables. Hope you find it useful!