Array Destructing

·

3 min read

Let's say we have an array that contains five numbers, like this:

let array1 = [1, 2, 3, 4, 5]

To get the elements from the array, we can do something like getting the number according to its indexes:

array1[0];
array1[1];
array1[2];
array1[3];
array1[4];

But this method is old and clunky, and there is a better way to do it – using array destructuring. It looks like this:

let [ indexOne, indexTwo, indexThree, indexFour, indexFive ] = array1;

Both methods above will yield the same result:

Now, we have five elements in the array, and we print those. But what if we want to skip one element in between?

Now, we have five elements in the array, and we print those. But What if we want to skip one element in between?

let [ indexOne, indexTwo, , indexFour, indexFive ] = array1;

console.log(indexOne);
console.log(indexTwo)
console.log(indexFour)
console.log(indexFive)

It will print :-

1
2
4
5

You can see that we are not getting the third element because we have set it as empty.

What is Object Destructuring in JavaScript?

let object = {
    name: "Nishant",
    age: 24, 
    salary: 200,
    height: '20 meters',
    weight: '70 KG'
}

Let's say we want the name, salary, and weight from this object to be printed out in the console.

console.log(object.name)
console.log(object.salary)
console.log(object.weight)

We can get them using the keys, which are name, salary, and weight.

But this code becomes difficult to understand sometimes. That's when destructuring comes in handy:

let { name, salary, weight } = object;

console.log(name)
console.log(salary)
console.log(weight)

To correct that issue, we can set default values when we are destructuring the object.

let object = {
    name: "Nishant",
    age: 24, 
    height: '20 meters',
    weight: '70 KG'
}

let { name, salary = 200, weight } = object;

console.log(name)
console.log(salary)
console.log(weight)

How to Use Object Destructuring with Functions

Let's say we have a function that prints all the data in the array to the console.

let object = {
    name: "Nishant",
    age: 24, 
    salary: 300,
    height: '20 meters',
    weight: '70 KG'
}

function printData(){

}

printData(object)

We are passing the object as a parameter in the function when it gets called:

let object = {
    name: "Nishant",
    age: 24, 
    salary: 300,
    height: '20 meters',
    weight: '70 KG'
}

function printData(object){
    console.log(object)
}

printData(object)

But again, we can do the same using destructuring.

let object = {
    name: "Nishant",
    age: 24, 
    salary: 300,
    height: '20 meters',
    weight: '70 KG'
}

function printData({name, age, salary, height, weight}){
    console.log(name, age, salary, height, weight)
}

printData(object)

Here, we are destructuring the object into name, age, salary, height and weight in the function parameters and we print everything on the same line.