The destructuring assignment syntax extracts object properties and assigns them to variables.
let {firstName, lastName} = person; |
It can also extract values from arrays and other iterable objects.
let [firstName, lastName] = person; |
// Create an Object const person = { firstName: “John”, lastName: “Doe”, age: 50 }; // Destructuring let {firstName, lastName} = person; |
The order of the properties is not important.
// Create an Object const person = { firstName: “John”, lastName: “Doe”, age: 50 }; // Destructuring let {lastName, firstName} = person; |
Note: Destructuring is non-destructive; it does not modify the original object. |
We can set default values for properties that may be missing.
// Create an Object const person = { firstName: “John”, lastName: “Doe”, age: 50 }; // Destructuring let {firstName, lastName, country = “US”} = person; |
// Create an Object const person = { firstName: “John”, lastName: “Doe”, age: 50 }; // Destructuring let {lastName : name} = person; |
One application of destructuring is extracting characters from a string.
// Create a String let name = “W3Schools”; // Destructuring let [a1, a2, a3, a4, a5] = name; |
Note: Destructuring can be applied to any iterable. |