Destructuring assignment in JavaScript

The Destructuring assignment was introduced in ES6. Destructuring assignment makes extracting value from the array and extracting properties from an object very easy.

Let us have a look at an example.


var cars = ["BMW","TOYOTA","MARUTI", "TRUCK", "JEEP"];

//without destructuring assignment 
var bestCar = data[0];
var goodCar = data[1];
var avgCar = data[2];
console.log(bestCar); //output: "BMW"
console.log(goodCar); //output: "TOYOTA"
                    

In the above example, if you need to extract value from an array, you need to assign them to variable one by one. First, we will see the destructuring assignment in an array.

Destructuring Assignment in Array

Please have a look at the below code to understand the basic destructuring assignment in an array.


var cars = ["BMW","TOYOTA","MARUTI", "TRUCK", "JEEP"];

var [bestCar, goodCar, avgCar, heavyVehicle, offRoadVehicle] = cars;
console.log(besCar); // output: "BMW"
console.log(goodCar); // output: "TOYOTA"
console.log(avgCar); // output: "MARUTI"
console.log(heavyVehicle); // output: "TRUCK"
console.log(offRoadVehicle); // output: "JEEP"
                    

In the above code, you can see how destructuring assignment works. You don't have to do one thing over and over like the previous example.
In the destructuring assignment operator, variables are assigned values from left to right. So the first variable gets the first value, the second gets the second value.

You can directly assign an array like below.


var [bestCar, goodCar, avgCar, heavyVehicle, offRoadVehicle] = ["BMW","TOYOTA","MARUTI", "TRUCK", "JEEP"];
console.log(besCar); // output: "BMW"
console.log(offRoadVehicle); // output: "JEEP"
                    

Skip values in Destructuring assignment

You can also skip values.


var [bestCar,,,, offRoadVehicle] = ["BMW","TOYOTA","MARUTI", "TRUCK", "JEEP"];
console.log(besCar); // output: "BMW"
console.log(offRoadVehicle); // output: "JEEP"

var [,,avgCar,heavyVehicle,] = ["BMW","TOYOTA","MARUTI", "TRUCK", "JEEP"];
// Determine the output your self.
                    

In the above example, we have skipped 3 values. So there are four semicolons between two variables ( three spaces ).

What if there are more variables then values in an array? Let us check.


var [bestCar, goodCar, avgCar, heavyVehicle, offRoadVehicle, anotherAvgCar] = ["BMW","TOYOTA","MARUTI", "TRUCK", "JEEP"];
console.log(besCar); // output: "BMW"
console.log(offRoadVehicle); // output: "JEEP"
console.log(anotherAvgCar); // output: undefined
                    

Do you see? any extra variable will be undefined.

Defalut values in destructuring assignment

What if you don't know anything about how many values are there in array? Then you can assign default values in the destructuring assignment.


var [bestCar, goodCar, avgCar, heavyVehicle, offRoadVehicle="COMPASS", anotherAvgCar="some_car_brand"] = ["BMW","TOYOTA","MARUTI", "TRUCK", "JEEP"];
console.log(besCar); // output: "BMW"
console.log(offRoadVehicle); // output: "JEEP"
console.log(anotherAvgCar); // output: "some_car_brand"
                    

In the above code, we have assigned default values to offRoadVehicle and anotherAvgCar variables. But offRoadVehicle will be assigned the value JEEP but after that, there is no value in an array. So anotherAvgCar will have its default value some_car_brand.

Declare variable before destructuring assignment

Declaring the variables before the destructuring assignment.


var bestCar, goodCar
[bestCar, goodCar] = ["BMW","TOYOTA","MARUTI", "TRUCK", "JEEP"];
console.log(besCar); // output: "BMW"
console.log(goodCar); // output: "TOYOTA"

[bestCar, goodCar, avgCar] =  ["BMW","TOYOTA","MARUTI", "TRUCK", "JEEP"];
console.log(avgCar); //output: "MARUTI" if it is not "strict mode"
console.log(avgCar); //output: error if it is "strict mode"
                    

In the above code, we have not declared avgCar variable. It will give an error in strict mode.

Rest pattern in destructuring assignment

What if you need to assign values to only some variables and remaining values should be assigned to other variables as an array?


var [bestCar, ...otherCars] = ["BMW","TOYOTA","MARUTI", "TRUCK", "JEEP"];
console.log(besCar); // output: "BMW"
console.log(otherCars); // output: ["TOYOTA","MARUTI", "TRUCK", "JEEP"]

var [a,b,...c] = [1,2];
//check what is the value of c?
                    

In the above code, we have used ... ( rest pattern ). So otherCars will have an array with remaining values.

Swap values using destructuring assignment

You can use the destructuring assignment to swap the values of variables.


var a = 2, b = 3;
[b,a] = [a,b];
console.log(a); //output: 2
console.log(b); //output: 3

//traditionally
var c = b;
b = a;
a = c;
                    

Destructuring assignment with string

You can have any iterables on the right-hand side of the destructuring assignment. Let us use string.


var [a,b,...c] = "This is";
console.log(a); //output: "T"
console.log(b); //outupt: "h"
console.log(c); //outupt: ["i","s"," ","i","s"]
                    

Assign values to object properties

You can have anything assignable to the left-hand side of the destructuring assignment. Let us use an object.


var obj = {};
[obj.firstName, obj.lastName] = ["John","Doe"];
console.log(obj.firstName); //output: "John"
console.log(obj.lastName); //output: "Doe"
                    

Destructuring assignment in Object

Destructuring assignment works with objects just like it works with arrays. The basic syntax is below.


var {property1, property2} = { property1:..., property2:..., ...};
                    

Let us have a look at an example.


var car = {
    color: "red",
    company: "kai",
    tyres: "4"
};

var {color, tyres} = car;
console.log(color); //output: "red"
console.log(tyres); //output: "4"
                    

In above code, car.color and car.tyres will be assigned to their corresponding variables.

In array, an order was important but in an object, order does not matter. You can use var {tyres, color} = car;. The output will be the same.

Default value in object destructuring assignment

Just like arrays, default values in object destructuring works the same way.


var car = {
    color: "red",
    company: "kai",
    tyres: "4"
};

var {color = "black", tyres, name="car_name"} = car;
console.log(color); //output: "red"
console.log(tyres); //output: "4"
console.log(name); //output: "car_name"
                    

In the above code, car object does not have a name property. We have assigned a default value in the destructuring assignment.

Change name of variable in destructuring assignment

If you want to assign the property to the variable with a different name, you need to use propertyName:variableName in destructuring assignment operator. Let us have a look at an example.


var car = {
    color: "red",
    company: "kai",
    tyres: "4"
};

var {color: c, company, tyres: t} = car;
console.log(c); //output: "red"
console.log(t); //output: "4"
console.log(company); //output: "kai"
                    

In the above code, car.color property is assigned to variable c. car.tyres assigned to variable t.

Combining default value and change name

You can combine default value and change the name in the destructuring assignment. Check out the example below.


var car = {
    color: "red",
    company: "kai",
    tyres: "4"
};

var {color: c, company, tyres: t, name: n = "car_name"} = car;
console.log(c); //output: "red"
console.log(t); //output: "4"
console.log(company); //output: "kai",
console.log(n); //output: "car_name"
                    

Rest pattern in destructuring object

Same as an array, you can use rest pattern ... to save the other properties into an object. Let us have a look at an example.


var car = {
    color: "red",
    company: "kai",
    tyres: "4"
};

var {color, ...otherProperties} = car;
console.log(color); //output: "red"
console.log(otherProperties.tyres); //output: "4"
console.log(otherProperties.company); //output: "kai",
                    

Declare variable before destructuring object

Let us have a look at an example.


var car = {
    color: "red",
    company: "kai",
    tyres: "4"
};
var color, tyres;
{color, tyres} = car; // error 
                    

The above code will give an error. Because JavaScript will consider code between {...} as a separate code. JavaScript considers it a block. If you need to declare a variable before the destructuring assignment, use it as shown in the below example.


var car = {
    color: "red",
    company: "kai",
    tyres: "4"
};
var color, tyres;
({color, tyres} = car);
console.log(color); //output: "red" 
                    

Complex destructuring assignment

Normally, objects are not simple while working with JavaScript. Let us have a look at an example with a more complex object destructuring assignment.


var car = {
    color: "red",
    company: "kai",
    tyres: "4",
    owner: {
        firstName: "John",
        lastName: "Doe"
    },
    services: [1,2,3,4]
};

var {
    color,
    owner: {
        firstName,
        lastName
    },
    services: [firstService, secondService,,lastService],
    ...otherProperties
} = car;
console.log(color); //output: "red"
console.log(firstName); //output: "John"
console.log(lastName); //output: "Doe"
console.log(firstService); //output: 1
console.log(lastService); //output: 4
console.log(otherProperties.tyres); //output: "4"
console.log(otherProperties.company); //output: "kai"
                    

Conclusion

In this section, you learned about the destructuring assignment with an array and destructuring assignment with an object.
In next section, you will learn about spread operator in JavaScript.