DEV Community

Cover image for Object Destructuring
Manav Misra
Manav Misra

Posted on • Updated on

Object Destructuring

Object destructuring allows us to 'pull out' specific named πŸ”‘s or properties from an object literal and bind values to variables.

This can save us some typing because we don't need to use . to access these values.

Destructuring and Renaming

As we destructure, we can choose to bind to a variable with a different name.

The destructuring must match the name of the πŸ”‘ in the original object. It's the part after the : that will be new 'custom' variable name.

Nested Destructuring

The destructuring process can continue as we drill down into nested objects.

You can also rename with nested destructuring.

Destructured Function Parameters

Given some function that is expecting to receive an object, we an apply destructuring to avoid using .s.

⚠️ 'References' vs 'Copies/Values'

This doesn't pertain directly to destructuring, but be aware of JS's unique behavior when it comes to mutations.

In the above code πŸ‘†πŸ½, we destructured and renamed address. However, me was still mutated; both of the objects have the 'zip plus 4.'

With destructuring, the same rules regarding JS Objects sharing memory references still applies.

With primitives, we don't need to worry.

The string for name was destructured. Because of how JS manages primitives, a new 'copy' of this value was created (no shared references for primitives), and original value in me was unchanged.

Top comments (0)