DEV Community

loading...
Cover image for Object Destructuring

Object Destructuring

codefinity profile image Manav Misra ・1 min read

Object destructuring allows us to 'pull out' specific named πŸ”‘s 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.

Discussion (0)

pic
Editor guide