It’s Time To Destructure Objects in JavaScript

Prefer to watch the video?

Did you know how to destructure an object in JavaScript?

Looking to learn something new in JavaScript? Here is destructuring assignment for you.

What is Destructuring Assignment?

I know you want a technical explanation. However, I will explain it in simple words. The ability to define and assign values of an object without accessing the values or properties of an object.

Let me show you. Below we have a car object:

const car = {
   id: 94521,
   make:  'Ford',
   model: 'Mustang',
   year: 2016
 }

If you want to store any of the properties in variable, you would do something along these lines:

const carId = car.id;
const make = car.make;
const model = car.model;
const carYear = car.year;

In that way you could use any of those variables if any of those values are used over and over within your code, which is fine. However, by destructuring the car’s object, you can take advantage of the car’s properties and use them to generate your new variable:

const { make, id, model, year } = car;

Isn’t it cool?

“Andres, what if I have an existing id variable within my function? I will get errors as I cannot have multiple variables with the same name if I decide to destructure the car’s object.”

Calm down my friend, I got you there. You can still define any variable name to the properties you want to access from the car’s object by adding a colon and the name you wish to give to your variable:

const { id: carId } = car;

In that way, we can have a variable called carId instead of id. Therefore, you will avoid conflicts if you have an existing id variable in your process.

This is handy especially when you need to use specific data that is retrieved from a function into another function without the need to store the whole object in a variable.

Async function getCar(id) {
   // getting data from the database
   .
   .
   .
   const record = await db.execute(query);
   return record;
   // which is the same as the following below
   // return {
   //  id: record.id,
   //  make: record.make,
   //  model: record.model,
   //  year: record.year,
   // };
   //
 }

 function getCarName(carId) {
   const { make, model, year } = await getCar(carId);
   return `${make} ${model} year: ${year}`;
 }

If you noticed, in our method getCarName we didn’t have to use the id of the car to generate the name.

‍“Andrés, what would happen if the getCar method doesn’t find any records in the database? What kind of values will it assign while destructuring a car object that doesn’t have a make property?”

‍Probably you are not going to come up with that question until you get an error. I’m telling you by experience.

‍However, if you can come up with such question, I can come up with an answer.

You can assign a default value while destructuring an object in the following way:

const { make = 'Hyundai' } = car;

In this way, the make of the car will default to “Hyundai” if the car doesn’t have any make property. You can still define whatever name you want to your variable as well as a default value:

const { make: carMake = 'Hyundai' } = car;

“Andres: Aren’t Array objects in JavaScript? Does object destructuring work with arrays?”

Yes, you are right. Arrays are also objects in JavaScript. A special type of object. Do you remember accessing the values of an array like this?

const players = ['Player 1', 'Player 2', 'Player 3', 'Player 4', 'Player 5'];
const playerOne = players[0];
const playerTwo = players[1];
const playerThree = players[2];
const playerFour = players[3];
const playerFive = players[4];

You could still destructure your array in the following manner:

const [
   playerOne, // ‘Player 1’
   playerTwo, // ‘Player 2’
   playerThree, // ‘Player 3’
   playerFour, // ‘Player 4’
   playerFive // ‘Player 5’
 ] = players;

Important: The values will be assigned in the order the items are in the array.

‍And before you ask, you can still get one item of your array as well like this:

const [ playerOne ] = players;

Also, you could separate one item from the array and generate another array from the rest of the items:

const [ playerOne, …otherPlayers ] = players;
// playerOne - 'Player 1';
// otherPlayers = ['Player 2', 'Player 3', 'Player 4', 'Player 5'];

You can also skip any item of the array, i.e, in case you don’t have to access the first item of the array but the second item, you only need to separate the destructured variables with a comma, and don’t assign a name to the “skipped” items of the original array:

const [, playerTwo, , …otherPlayers ] = players;
 // playerTwo - 'Player 2';
 // otherPlayers = ['Player 4', 'Player 5'];

And finally, if you need to assign a default value it should look like this:

const [, two,,,,,any = 'Any Player'] = players
 // any = 'Any Player'

Isn’t destructuring assignment neat?‍

Now that you know it, go ahead and use it on your projects. Once you start using it, you will fall in love and will end up using it over and over.