Register to get access to free programming courses with interactive exercises

Destructuring JS: Objects

Objects in real-world applications often have a complex structure. Objects nested in objects nested in objects, and so on. It isn't convenient to use deeply nested objects directly if you need to access it repeatedly:

const greeting = `${user.company.name} was founded in ${user.company.createdAt}`;
console.log(greeting);

Developers try to reduce such code and create intermediate constants for nested data:

const company = user.company;
const greeting = `${company.name} was founded in ${company.createdAt}`;
console.log(greeting);

The more calls there are to nested data, the more useful this technique is. But data extraction itself can become cumbersome if there is a lot of data. An example from real life:

const response = {
  data: {
    type: 'photos',
    id: '550e8400-e29b-41d4-a716-446655440000',
    attributes: {
      title: 'Ember Hamster',
      src: 'http://example.com/images/productivity.png'
    },
    relationships: {
      author: {
        links: {
          related: 'http://example.com/articles/1/author'
        },
      },
    },
    links: {
      self: 'http://example.com/photos/550e8400-e29b-41d4-a716-446655440000'
    },
  },
};

This is data from a fictional application represented in the jsonapi format. It's used, for example, on Hexlet for interaction between the server and client parts of the site. This data is extracted and displayed within the client. Imagine what the code for extracting the innards of this structure could look like:

const user = response.data.attributes;
const links = response.data.links;
const author = response.data.relationships.author;

The more data you need to get and the deeper it's located, the more monotonous and repetitive code you have to write. There's nothing particularly wrong with this — everyone used to do it this way. But as the language evolved, it became possible to write much better code.

Destructuring is a special syntax that allows you to extract parts of compound data. This is a handy way to break down objects into parts. It allows you to shorten the code and make it more understandable.

const person = { firstName: 'Rasmus', lastName: 'Lerdorf', manager: true };

const { firstName, manager } = person;

console.log(firstName); // => 'Rasmus'
console.log(manager); // => true

https://repl.it/@hexlet/js-objects-destructuring-object-destructuring-en

Destructuring bears similarities to creating an object. It uses precisely the same syntax, but instead of creating an object, it breaks it down into parts. Destructuring allows you to "break down" an object piece by piece, i.e., you don't have to extract it all at once. The object has three properties in the example above, but only two are retrieved. The order of properties is not important when extracting.

You can also rename when destructuring. This is necessary if a constant with the same name has already been defined above.

const manager = /* ... */; // name taken

const person = { firstName: 'Rasmus', lastName: 'Lerdorf', manager: true };

const { manager: isManager } = person;

console.log(isManager); // => true

If there are no properties in the object, destructuring allows you to set default values for such properties:

const person = { firstName: 'Rasmus', lastName: 'Lerdorf' };

console.log(person.manager); // undefined
const { manager = false } = person;
console.log(manager); // => false

https://repl.it/@hexlet/js-objects-destructuring-default-value-en

Destructuring can be nested. It allows you to extract parts of objects at any depth. Therefore, our example above can be rewritten as follows:

// const user = response.data.attributes;
// const links = response.data.links;
// const author = response.data.relationships.author;

const { links, attributes: user, relationships: { author } } = response.data;

The spread operator has a similar but inverted operator called rest. It can be used during destructuring to collect all the remaining properties into one object:

const user = { name: 'Tirion', email: 'support@hexlet.io', age: 44 };

const { name, ...rest } = user;

console.log(rest);
// => { email: 'support@hexlet.io', age: 44 }

Although destructuring is optional and does not affect the architecture of your programs, it makes the code cleaner and clearer (if you don't go too far with this).


Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.