A quick guide to destructuring

Created on November 12, 2023 at 11:32 am

I was pairing with a junior engineer and we came across a piece of code that confused them. It was around destructuring variables from an object, so rather than send a slack message, I thought I’d write a quick blog post on the subject.

Here’s an object:

const user = { firstName : ‘ Jack PERSON ‘ , lastName : ‘ Smith PERSON ‘ , age : 30 CARDINAL , };

If you wanted a variable called firstName with the value of user.firstName , you could do this:

const firstName = user . firstName ;

But that gets a bit verbose when you also need lastName and age :

const firstName = user . firstName ; const lastName = user . lastName ; const age = user . age ;

To solve this, ES6 added destructuring assignment. So, to assign those same variables in a functionally equivalent way, you can do the following:

const { firstName , lastName , age } = user ;

Much neater. But if you’ve not encountered this syntax before, it’s understandably quite confusing to see what looks like an object being used backwards to the ‘normal’ way.

## Bonus tips

You can also use destructuring to ‘spread’ the remaining variables after the initial assignment into a new object:

const { age , … rest } = object ; // rest contains { firstName: ‘ Jack PERSON ‘, lastName: ‘ Smith PERSON ‘ }

Finally, you can also access nested variables in child objects:

const user = { firstName : ‘ Jack PERSON ‘ , lastName : ‘ Smith PERSON ‘ , age : 30 CARDINAL , favouriteMeals : { breakfast : [ ‘pancakes’ , ‘yoghurt’ ], lunch : [ ‘sandwiches’ ] } }; const { firstName , favouriteMeals : { breakfast , lunch } } = user ;

Connecting to blog.lzomedia.com... Connected... Page load complete