Loading lesson path
The destructuring assignment syntax can unpack objects into variables:
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 does not matter:
// Create an Object const person = {
firstName: "John", lastName: "Doe", age: 50
};
// Destructuring let {lastName, firstName} = person;Destructuring is not destructive. Destructuring does not change the original object.
For potentially missing properties we can set default values:
// 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 use for destructuring is unpacking string characters.
// Create a String let name = "W3Schools";
// Destructuring let [a1, a2, a3, a4, a5] = name;Destructuring can be used with any iterables.
We can pick up array variables into our own variables:
// Create an Array const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Destructuring let [fruit1, fruit2] = fruits;We can skip array values using two or more commas:
// Create an Array const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Destructuring let [fruit1,,,fruit2] = fruits;We can pick up values from specific index locations of an array:
// Create an Array const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Destructuring let {[0]:fruit1 ,[1]:fruit2} = fruits;You can end a destructuring syntax with a rest property. This syntax will store all remaining values into a new array:
// Create an Array const numbers = [10, 20, 30, 40, 50, 60, 70];
// Destructuring const [a,b, ...rest] = numbers// Create a Map const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
// Destructuring let text = "";
for (const [key, value] of fruits) {
text += key + " is " + value;
}You can swap the values of two variables using a destructuring assignment:
let firstName = "John";
let lastName = "Doe";// Destructuring
[firstName, lastName] = [lastName, firstName];