JavaScript
Object destructuring
Learn to extract object properties into variables with a shorthand.
Object destructuring
Destructuring is a shorthand for pulling an object's properties into variables in one line. You write variable names inside curly braces; JavaScript finds the property with the same name and copies its value.
For example, const { name } = user takes the value of user.name into a name variable. It is the same as const name = user.name, only shorter and clearer.
The same-name rule
In destructuring, the variable name must be the same as the property name. When you write const { title } = book, JavaScript looks for the book.title property. If you want a different variable name, you rename with a colon (covered later).
You can pull several properties in one line, separated by commas: const { name, email, age } = user. Order does not matter; each name is independent.
Exercise Extract user details
Create an object called user with name and email properties. Use destructuring to pull name and email into variables. Then log each one separately with console.log.
Show example solution
const user = { name: "Alex", email: "alex@example.com" };
const { name, email } = user;
console.log(name);
console.log(email);
Test yourself
-
What does `const { title } = book` create?
- A new object called `book`
- A variable called `title`
- It deletes the `book.title` property
- An array called `title`
Show answer
A variable called `title` — Correct. The value of `book.title` is copied into a `title` variable.
-
Complete the object destructuring
const user = { name: "Alex", email: "alex@example.com" };
const { name, email } = ____;
console.log(name, email);
Show answer
const user = { name: "Alex", email: "alex@example.com" };
const { name, email } = user;
console.log(name, email);
-
Which is valid object destructuring syntax?
- `const [name] = user`
- `const { name } = ( user )`
- `const ( name ) = user`
- `const { name } = user`
Show answer
`const { name } = user` — Correct. Curly braces connect to the source object with an equals sign.
-
Match the concepts
- destructuring
- Shorthand for extracting properties
- curly braces
- Starts the object pattern
- same-name rule
- Variable matches property name
Next lesson: Array destructuring