- Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables.
- Destructuring also works great with complex functions that have a lot of parameters, default values.
Array Destructuring
// we have an array with the name and surname
let arr = ["Ilya", "Kantor"]
// Destructuring assignment
let [firstName, surname] = arr;
alert(firstName); // Ilya
alert(surname); // Kantor
- It works great when combined with split or other array-returning methods:
let [firstName, surname] = "Ilya Kantor".split(' ');
// Unwanted elements of the array can also be thrown away via an extra comma:
// First and second elements are not needed
let [, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert(title); // Consul
// We can use it with any iterable, not only arrays:
let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);
// We can use any “assignables” at the left side.
let user = {};
[user.name, user.surname] = "Ilya Kantor".split(' ');
- We can use
Object.entries(obj)
with destructuring to loop over keys-and-values of an object or a map:
let user = {
name: "John",
age: 30
};
// Or as a Map:
let user = new Map();
user.set("name", "John");
user.set("age", "30");
// loop over keys-and-values
for (let [key, value] of Object.entries(user)) {
alert(`${key}:${value}`); // name:John, then age:30
}
The Rest ‘…’
- If we want not just to get first values, but also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "...":
- The value of rest is the array of the remaining array elements.
- We can use any other variable name in place of rest, just make sure it has three dots before it and goes last in the destructuring assignment.
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert(name1); // Julius
alert(rest[0]); // Consul
alert(rest.length); // 2
Default Values
- If there are fewer values in the array than variables in the assignment, there will be no error.
- Absent values are considered undefined.
- If we want a “default” value to replace the missing one, we can provide it using =:
let [firstName, surname] = [];
alert(firstName); // undefined
// Default values
let [name = "Guest", surname = "Anonymous"] = ["Julius"];
alert(name); // Julius (from array)
alert(surname); // Anonymous (default used)
- Default values can be more complex expressions or even function calls.
- They are evaluated only if the value is not provided.
// Runs only prompt for surname
let [name = prompt('name?'), surname = prompt('surname?')] = ["Julius"];
alert(name); // Julius (from array)
alert(surname); // whatever prompt gets
Object Destructuring