JavaScript Destructuring
- Previous page JS type conversion
- Next page JS bitwise operations
Destructuring assignment syntax
The destructuring assignment syntax unpacks object properties into variables:
let {firstName, lastName} = person;
It can also unpack arrays and any other iterable objects:
let [firstName, lastName] = person;
Object destructuring
Example
// Create an object const person = { firstName: "Bill", lastName: "Gates", age: 50 }; // Destructuring let {firstName, lastName} = person;
The order of properties does not matter:
Example
// Create an object const person = { firstName: "Bill", lastName: "Gates", age: 50 }; // Destructuring let {lastName, firstName} = person;
Note:
Destructuring is not destructive.
Destructuring does not change the original object.
Object default values
For missing properties, we can set default values:
Example
// Create an object const person = { firstName: "Bill", lastName: "Gates", age: 50 }; // Destructuring let {firstName, lastName, country = "US"} = person;
Object property alias
Example
// Create an object const person = { firstName: "Bill", lastName: "Gates", age: 50 }; // Destructuring let {lastName: name} = person;
String destructuring
One use of destructuring is to unpack string characters.
Example
// Create a string let name = "W3Schools"; // Destructuring let [a1, a2, a3, a4, a5] = name;
Note:
Destructuring can be used for any iterable object.
Array destructuring
We can extract array variables into their own variables:
Example
// Create an array const fruits = ["Bananas", "Oranges", "Apples", "Mangos"]; // Destructuring let [fruit1, fruit2] = fruits;
Skipping array values
We can use two or more commas to skip array values:
Example
// Create an array const fruits = ["Bananas", "Oranges", "Apples", "Mangos"]; // Destructuring let [fruit1,,,fruit2] = fruits;
Array position values
We can extract values from specific index positions in an array:
Example
// Create an array const fruits = ["Bananas", "Oranges", "Apples", "Mangos"]; // Destructuring let {[0]: fruit1, [1]: fruit2} = fruits;
Rest properties
You can use the rest properties at the end of destructuring syntax.
This syntax will store all remaining values into a new array:
Example
// Create an array const numbers = [10, 20, 30, 40, 50, 60, 70]; // Destructuring const [a, b, ...rest] = numbers;
Destructure Map
Example
// 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; }
Swap JavaScript variables
You can use destructuring assignment to swap the values of two variables:
Example
let firstName = "Bill"; let lastName = "Gates"; // Destructuring [firstName, lastName] = [lastName, firstName];
- Previous page JS type conversion
- Next page JS bitwise operations