Destructuring
Destructuring is a way to extract data from arrays and objects briefly and neatly, without extra code. Instead of several lines of obj.prop you create the variables you need in a single expression, by property name for objects and by position for arrays.
Theory
TL;DR
- Objects are destructured by property name:
const { name, age } = user;. - Arrays are destructured by position:
const [a, b] = arr;. - A variable can be renamed:
const { name: userName } = user;. - A default value can be supplied:
const { city = 'Paris' } = user;. - Nested structures unpack the same way:
const { address: { city } } = user;. - Rest collects the remainder:
const [first, ...rest] = arr;.
Quick example
Before ES6 you had to write this:
const user = { name: 'Alex', age: 25 };
const name = user.name;
const age = user.age;
console.log(name, age); // Alex 25With ES6 the same thing fits on one line:
const user = { name: 'Alex', age: 25 };
const { name, age } = user;
console.log(name, age); // Alex 25Now name and age have been created automatically as variables with the same names as the object properties.
Destructuring objects
Pull out only the properties you need:
const { name } = user;
console.log(name); // AlexRename the variables:
const { name: userName, age: userAge } = user;
console.log(userName, userAge); // Alex 25Default values kick in when the property is missing or undefined:
const { city = 'Paris' } = user;
console.log(city); // ParisNested objects unpack with the same syntax:
const user = {
name: 'Alex',
address: { city: 'Paris', zip: 12345 }
};
const { address: { city, zip } } = user;
console.log(city, zip); // Paris 12345Destructuring arrays
For arrays the values are taken by position, not by name:
const arr = [10, 20, 30];
const [a, b, c] = arr;
console.log(a, b, c); // 10 20 30Skipping elements is done with an empty slot between commas:
const [first, , third] = [1, 2, 3];
console.log(first, third); // 1 3Default values:
const [x = 0, y = 0, z = 0] = [5, 10];
console.log(x, y, z); // 5 10 0The rest operator collects every remaining element into a new array:
const [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest); // [2, 3, 4]Mixed destructuring
Objects and arrays can be combined in a single expression:
const user = {
name: 'Tim',
hobbies: ['music', 'coding'],
address: { city: 'Berlin' }
};
const {
name,
hobbies: [firstHobby],
address: { city }
} = user;
console.log(name, firstHobby, city); // Tim music BerlinDestructuring in functions
Unpacking an object right in the argument saves you from a long parameter list:
function greet({ name, age }) {
console.log(`Hello, ${name}! You are ${age}.`);
}
greet({ name: 'Alex', age: 25 }); // Hello, Alex! You are 25.Default values in parameters, together with = {} for the case where no argument was passed at all:
function connect({ host = 'localhost', port = 3000 } = {}) {
console.log(`Connecting to ${host}:${port}`);
}
connect(); // Connecting to localhost:3000Unpacking whatever a function returned is just as convenient:
function getUser() {
return { name: 'Alex', age: 25 };
}
const { name, age } = getUser();
console.log(name, age); // Alex 25Why destructuring is useful
| Benefit | Explanation |
|---|---|
| Short and clean code | Fewer repetitions of obj.prop |
| Convenient function arguments | No need to pass a pile of parameters |
| Flexibility | You can set defaults, rename and skip |
| Used constantly in React | For example: const { user, loading } = useAuth(); |
A short syntax summary:
| Kind | Syntax | Example |
|---|---|---|
| Object | { prop1, prop2 } = obj | const { name, age } = user; |
| Array | [a, b] = arr | const [x, y] = [10, 20]; |
| Nested | { nested: { prop } } = obj | const { info: { id } } = data; |
| Rest | { a, ...rest } = obj or [a, ...rest] = arr | const { id, ...other } = user; |
| Default | { prop = value } or [x = 0] | const { city = 'Paris' } = user; |
Common mistakes
- Confusing renaming with a type annotation.
const { name: userName } = usercreates a variableuserName, it does not declare a type, and nonamevariable exists afterwards. - Expecting a default to apply to
null. Defaults only apply when the value isundefined, so{ city = 'Paris' }oncity: nullyieldsnull. - Destructuring
undefinedornull.const { a } = undefinedthrows aTypeError; for parameters the= {}fallback saves you. - Forgetting that arrays unpack by position. The variable names in
[a, b]mean nothing, the order decides everything. - Starting a line with
{when assigning withoutconst. The expression{ a } = obj;is read as a block; wrap it in parentheses:({ a } = obj);.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.