🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Destructuring Objects

Destructuring is a short way to pull named values out of an object. One line with curly braces takes several values at once.

Pull two values at once

One pattern pulls both values. Each name matches a property name.

const user = { name: "Ana", age: 28 };
const { name, age } = user;
console.log(name);
console.log(age);

Take only what is needed

The pattern can take one value and leave the rest. The object still holds the values that were not taken.

const book = { title: "Dune", author: "Frank Herbert", pages: 412 };
const { title } = book;
console.log(title);
console.log(book.pages);

Pull from a nested object

Destructuring works in two steps for a nested object. The first step takes the inner object, and the second step takes its values.

const order = { id: 7, buyer: { name: "Lee", city: "Portland" } };
const { buyer } = order;
const { name, city } = buyer;
console.log(name);
console.log(city);

Example

const movie = { title: "Arrival", year: 2016, rating: 8 };
const { title, year } = movie;
console.log(title);
console.log(year);
console.log(movie.rating);

Key points

  • Destructuring: pulling values out of an object or an array with one pattern
  • The names in the pattern must match the property names in the object.
  • Use destructuring to take only the values a line of code needs.
  • The object keeps all its properties after destructuring.
  • Each new variable holds the value from the matching property.

In this example, the pattern takes the title and the year out of the movie object. The rating stays in the object, so the last line reads it from the object itself.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does const { name, age } = user; do?