Destructuring
Destructuring assignment is introduced in ES6.
Destructuring is a method in which whenever we need only some of the items of an array or an object, we use the destructuring method.
Destructuring an array
Below examples will show the difference of with and without the destructuring method in an array.
In ordinary method
let vehicles = ["Car", "Bus", "Bike", "Bicycle"];
let vehicle1 = vehicles[0];
let vehicle2 = vehicle1[1];
let vehicle3 = vehicle1[2];
let vehicle4 = vehicle1[3];
By using the destructuring method
let vehicles = ["Car", "Bus", "Bike", "Bicycle"];
const [vehicle1, vehicle2, vehicle3, vehicle4] = vehicles;
Destructuring an object
In ordinary method
const vehicle = {
brand: "BMW",
type: "Sedan",
color: "black",
};
console.log(vehicle.brand, vehicle.type, vehicle.color);
By using the destructuring method
const vehicle = {
brand: "BMW",
type: "Sedan",
color: "black",
};
const { brand, type, color } = vehicle;
console.log(brand, type, color);
Note
When destructuring objects, it is mandatory to use same name for the variable corresponding to that of object properties.
Note
There is no specific order for declaring properties of an object while using the destructuring method.
Rest property
The ...rest
property will store all the objects or arrays remaining properties in a new object or array.
Syntax
const { a, ...others } = { a: 1, b: 2, c: 3 };
console.log(others);
const [a, ...others] = [1, 2, 3, 4];
console.log(others);
Note
The rest property must be last in pattern, consider using rest operator as a last element. And must not have a comma after the rest property.
const [a, ...others] = [1, 2, 3, 4, 5];
console.log(others);