Destructuring
- Node.js course
- Beginner
- Lesson 10/116
- 4 min
Learn to extract values from arrays and objects with destructuring.
What is destructuring?
Destructuring is a way to pull values out of an array or object into variables in a single line. It shortens long access code.
Object example: const { name, age } = user. This assigns user.name to name and user.age to age.
Array example: const [first, second] = colors. This assigns colors[0] to first and colors[1] to second.
Object destructuring
Curly braces are used for object destructuring. The variable names match the field names of the object.
Example: const user = { name: 'Alex', age: 28 }. Then writing const { name, age } = user gives you both name and age variables ready to use.
You can also extract only one field: const { name } = user. This extracts only name and ignores age.
Practice Extract values with destructuring
Define an object named user: name is 'Alex', age is 28. Use destructuring to extract name and age. Then call console.log(name) and console.log(age).
Starter code
const user = { name: "Alex", age: 28 };
// Extract name and age with destructuring
// Then log them with console.logSample solution
const user = { name: "Alex", age: 28 };
const { name, age } = user;
console.log(name);
console.log(age);Expected output
Alex 28
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does destructuring make easier?
- Creating arrays
- Defining functions
- Writing loops
- Assigning object properties to variables Correct answer
Explanation: Destructuring pulls object properties into variables.
2 Match the destructuring examples
| Term | Meaning |
|---|---|
const { name } = user |
Object destructuring |
const [a] = list |
Array destructuring |
const { x, y } = point |
Multiple object |
const [first, ...rest] |
Array with rest |
3 Destructuring syntax
const { name, age } = ____;
const { name, age } = user;
Explanation: name and age are extracted from user.