Destructuring
Destructuring lets you pull values out of an array or object and put them into separate variables in one line. It makes code shorter and appears in almost every modern project.
Arrays
List variables in square brackets on the left of =. They receive the array elements in order:
const [first, second] = ['apple', 'pear'];
console.log(first); // appleIt is the same as writing const first = fruits[0] and const second = fruits[1], only shorter.
Skipping and defaults
Skip an element by leaving an empty slot between commas. If the array has no such element, the variable gets its default value:
const [x, , z = 0] = [1, 2];
console.log(x, z); // 1 0Objects
Objects use curly braces. Variables receive the values of the properties with the same names:
const user = { name: 'Anna', age: 25 };
const { name, age } = user;
console.log(name); // AnnaOrder does not matter here — values are found by name.
Renaming and defaults
A colon gives the variable a different name, and = supplies a value for when the property is missing:
const user = { name: 'Anna' };
const { name: userName, city = 'not set' } = user;
console.log(userName, city); // Anna not setIn function parameters
Destructuring is often written right in the parameters. It shows at a glance which properties the function needs:
function describe({ name, age }) {
return `${name}, ${age}`;
}
console.log(describe({ name: 'Anna', age: 25 })); // Anna, 25Swapping values
Destructuring swaps two variables without a third one:
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1Common mistake
Destructuring null or undefined throws an error: you cannot take a property out of "nothing". This happens when a function is called without an argument. Here try...catch catches the error to show its type — it is covered in the chapter on errors:
function describe({ name }) {
return name;
}
try {
describe();
} catch (error) {
console.log(error.name); // TypeError
}If the object may be missing, give the whole parameter a default: function describe({ name } = {}). Then a call without an argument returns undefined instead of failing.