We can assign values from an array to our own variables.
// Create an Array const fruits = [“Bananas”, “Oranges”, “Apples”, “Mangos”]; // Destructuring let [fruit1, fruit2] = fruits; |
We can omit array values by using two or more commas.
// Create an Array const fruits = [“Bananas”, “Oranges”, “Apples”, “Mangos”]; // Destructuring let [fruit1,,,fruit2] = fruits; |
We can extract values from specific index positions in an array.
// Create an Array const fruits = [“Bananas”, “Oranges”, “Apples”, “Mangos”]; // Destructuring let {[0]:fruit1 ,[1]:fruit2} = fruits; |
You can conclude a destructuring statement with a rest property, which will collect 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] ]); // Destructing let text = “”; for (const [key, value] of fruits) { text += key + ” is “ + value; } |
You can swap the values of two variables using destructuring assignment.
let firstName = “John”; let lastName = “Doe”; // Destructing [firstName, lastName] = [lastName, firstName]; |