Destructuring
Often you need two or three lines from a form and then work with them separately. You copy them onto slips: the name onto the slip name, the age onto the slip age. In code, that is one line per property: const city = user.city.
The same work fits in one line:
const user = { name: "Ann", age: 30, city: "Oslo" };
const city = user.city;
const { name, age } = user;
console.log(name, age, city); // Ann 30 OsloLet's go through the example line by line:
const city = user.cityis the familiar form: one variable, one property.const { name, age } = usercreates two variables at once,nameandage, and puts the same-named properties ofuserinto them.console.logprintsAnn 30 Oslo.
Writing const { name, age } = user is called destructuring. The variables in the curly braces on the left get the properties with the same names from the object on the right. The names must match the keys: const { nme } = user gives undefined, because there is no property nme. The object itself does not change.
A slip gets a copy of the value, and the form stays as it was. Here the analogy stops working for nested objects: when a property holds an object, the variable gets a reference to it, like a shallow copy.
Default values
When a property is missing, the variable gets undefined. A value after = inside the braces, as in const { y = 0 } = point, replaces undefined. Default parameters of functions work the same way.
A property whose value is null or 0 stays as it is: the default value replaces only undefined.
Another name
A colon gives the variable another name: { x: left } puts the property x into the variable left. Left of the colon is the property's name, right of it the new variable's name, and no variable x appears.
Another name is needed when the property's name is already taken or says nothing about the data. For example, the program already has a variable x, and a second one with the same name cannot be declared.
Both forms combine inside one pair of braces. After const { x: left, y = 0 } = { x: 3 }, left holds 3, and y holds 0.
In function parameters
Destructuring also works in the parameter list. The function gets one object and takes it apart into variables at once:
function area({ width, height = 1 }) {
return width * height;
}
console.log(area({ width: 2, height: 3 })); // 6
console.log(area({ width: 5 })); // 5Let's go through it line by line:
areatakes apart its only parameter, an object, right in the parameter list.- The call
area({ width: 2, height: 3 })puts2intowidth,3intoheightand returns6. - In the second call, there is no property
height, and it gets the default value1: the result is5.
The order of properties in the argument does not matter: they are found by name. That is why a function with an object parameter is hard to call wrongly by mixing up the arguments.
Arrays
Square brackets on the left take an array apart by position. The first variable gets the element at index 0, the second the one at index 1. Array elements have no labels like the lines of a form, so the variable names can be anything: the position is what counts.
The same form helps in two more cases:
- swapping the values of two variables;
- taking apart the pairs from
Object.entries.
const [first, second] = [10, 20, 30];
console.log(first, second); // 10 20
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
for (const [key, value] of Object.entries({ x: 1, y: 2 })) {
console.log(key, value);
}
// x 1
// y 2The third element 30 in the first line goes nowhere. When there are more variables than elements, the extra ones get undefined.
In [a, b] = [b, a], the right side creates a new array from the old values. The left side takes it apart back into a and b. Interviewers often ask you to swap two values without a third variable.
In a loop over Object.entries, each pair is taken apart into key and value at once, with no entry[0] and entry[1].
Common mistake
A function that takes apart an object parameter was called without an argument:
function greet({ name }) {
return `Hi, ${name}`;
}
console.log(greet()); // ✗TypeError: Cannot destructure property 'name' of 'undefined' as it is undefined.Without an argument, the parameter is undefined, and undefined has no properties.
Give the parameter a default value: with function greet({ name = "guest" } = {}), the call greet() returns Hi, guest. The empty object {} replaces the missing argument, and name gets its default value.
Key points
const { name, age } = userputs properties into variables with the same names; a missing property givesundefined.{ y = 0 }sets a default value, and{ x: left }puts the propertyxinto the variableleft.const [first, second] = arrtakes an array apart by position, and[a, b] = [b, a]swaps the values.- An object parameter without an argument breaks the destructuring, so it gets the default value
= {}.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.