DEV Community

Cover image for Javascript - Destructuring the Thing!
Atif Aiman
Atif Aiman

Posted on

Javascript - Destructuring the Thing!

Salam, and well, hello everyone!

Have you ever thought about the data structure of an array or object, with the most complex structure, and try to call a parameter that lives deep inside the dungeon of the object? Well, students[4].subjects[2].information.lecturers[1] indeed seems horrifying, especially when you had to repeat the code throughout your codebases πŸ’€

There's a solution for that! But to understand how it works, we need to go for the conventional way first to see how it evolves into "destructuring". So, what is "destructure" in Javascript?


Destructuring

Destructuring

Well, time for imagination. A box. Full of items. Later, you have to remember each of them just to play with them. Instead of remembering where it locates inside the box, you unpack the box and name it accordingly, so it will be easier to play with them later on. And it is not necessary to unpack everything, you can just unpack whatever you need.

In Javascript, you can "unpack" whatever you need inside an object and arrays. Yes, both of them! But, how does it look like?

Anatomy of destructuring

There are three parts of destructuring that you need to pay attention to. First is, of course, the original object or array. It's impossible to destructure something that doesn't exist.


And here we come...

const team = {
  name: "Team Secret",
  region: "Europe",
  members: ["MATUMBAMAN", "Nisha", "zai", "YapzOr", "Puppey"],
  year: 2021,
  coach: "Heen",
  captain: "Puppey",
  isFinalist: true,
};
Enter fullscreen mode Exit fullscreen mode

Let us consider the object above is the one we want to play with. Object with 7 entries, with each of them, has different value types. Cool. So, how do we want to call the region, as an example?

console.log(team.region);
// Europe
Enter fullscreen mode Exit fullscreen mode

As easy as TI, right? Huh, I mean, ABC! Cool. Now, how about calling Nisha?

console.log(team.members[1]);
// Nisha
Enter fullscreen mode Exit fullscreen mode

Still easy. So, just imagine you have to call the same exact thing at multiple places, so how will it be?


...and we come from a long way...

From this point, instead, I want to call it the long way, I just want to call what is necessary. Not every entry in the team object will be used. So, getting the members...

const members = team.members;

console.log(members[2]);
// zai
Enter fullscreen mode Exit fullscreen mode

And now, I need members, captain, and name of the team.

const teamName = team.name;
const captain = team.captain;
const members = team.members;
Enter fullscreen mode Exit fullscreen mode

So, just imagine, if we deal with a big object, that means that the code above will be bigger as well if the need increases as well. But, just to give an idea, we rename the object values to the new variable declaration. Easier to read, but a bit redundant work here.

I need you to put attention to two things here. We call the original index (or key), and then rename it by declaring a new variable, so we don't need to call the object anymore, since the new variable is declared using the object values.

const teamName = team.name;
const captain = team.captain;
const members = team.members;
      -------    -------------
     rename       original index
Enter fullscreen mode Exit fullscreen mode

...to be better every day

Let's dive slowly to destructuring. The same idea that we discussed before, I will demonstrate how we use destructuring for better syntax.

const { members: teamMembers } = team;
       ---------  --------------
 original index     rename

console.log(teamMembers[0]);
// MATUMBAMAN
Enter fullscreen mode Exit fullscreen mode

With this, you don't need to use the standard declaration way and start using destructuring way. And, you can still access the object the normal way as well, since it doesn't change the original object. It just creates a new variable during destructuring.

const { members: teamMembers } = team;

console.log(teamMembers[0]);
// MATUMBAMAN

console.log(team.captain);
// Puppey
Enter fullscreen mode Exit fullscreen mode

Without renaming

There is a time, you feel that renaming is unnecessary, and that happens! If that is the case, you can just omit the renaming, and just use the original index (or key).

const { members } = team;

console.log(members[4]);
// Puppey
Enter fullscreen mode Exit fullscreen mode

As you can see, destructuring can be as simple as that! Just use the original key name, and you are good to go. So, let's destructure everything!

const {
  name,
  region,
  members,
  year,
  coach,
  captain,
  isFinalist,
} = team;
Enter fullscreen mode Exit fullscreen mode

And yes, as simple as that!

Destructure one and retain others

For this case, let's assume this is the case.

const members = team.members;
const otherInfo = {
  name: team.name,
  region: team.region,
  year: team.year,
  coach: team.coach,
  captain: team.captain,
  isFinalist: team.isFinalist,
};
Enter fullscreen mode Exit fullscreen mode

What have you noticed here? Well, we can see we declare members, which can later be simplified with the destructuring method. But how about the next one, which is otherInfo? It has everything the team has, except for members! So it has the rest of them after declaring members.

For this case, we will learn to use a spread operator, where it will take everything else, and put it inside a new name for it.

const {
  members,
  ...otherInfo
} = team;

console.log(otherInfo.coach);
// Heen
Enter fullscreen mode Exit fullscreen mode

Shorter, simpler, and easier to read, right? Since "the rest" didn't have any key it refers to, the way it writes is just ...rest. After spread operator (...), put any name you want.

You can also do a mix of everything!

const {
  members,
  captain: teamCaptain,
  year: competeYear,
  ...theRest
} = team;
Enter fullscreen mode Exit fullscreen mode

Everything has its beginning

There is a time, where the object key didn't exist, so you want to initialize it first. So, can we do that? Of course!

const {
  director,
} = team;
// This will return error, since director
// is not in `team` object

const {
  director = "John Yao",
} = team;
// This will not produce error, because
// the `director` will be initialized since
// director is not exist. Yet.
Enter fullscreen mode Exit fullscreen mode

Can we also use this to the existing key? The answer is yes!

const {
  coach = "Atif",
} = team;
// This will not produce error. However, you
// will get "Heen" later on, since coach is already
// has value in the object.
Enter fullscreen mode Exit fullscreen mode

Using this way, it will initialize it to "Atif", only when the coach isn’t existed or undefined.

Put everything in one place

const {
  members,
  captain: teamCaptain = "Aiman",
  year: competeYear,
  manager = "Cyborgmatt",
  ...theRest
} = team;

console.log(members[3]); // YapzOr
console.log(teamCaptain); // Pupper
// Team captain already initialized in the original object
console.log(competeYear); // 2021
console.log(manager); // Cyborgmatt
console.log(theRest.coach); // Heen
Enter fullscreen mode Exit fullscreen mode

And, how about the object inside the object?

const team = {
  name: "Team Secret",
  region: "Europe",
  members: ["MATUMBAMAN", "Nisha", "zai", "YapzOr", "Puppey"],
  year: 2021,
  coach: "Heen",
  captain: "Puppey",
  isFinalist: true,
  position: {
    core: ["MATUMBAMAN", "zai"],
    support: ["Puppey", "YapzOr"],
    mid: ["Nisha"],
  },
};

const {
  position: {
    core,
    support,
    mid,
  },
} = team;
Enter fullscreen mode Exit fullscreen mode

That's it! Just navigate through the nested object as usual. You can see the position parameter I added, and later I destructure by using position first and then destructure what is inside.

That is how you rock the object destructuring! But, how about arrays?


Destructuring in arrays

Do you notice that I keep on saying index/keys? Yup, the object has flexible indexing or what we call keys, so it's easy to destructure an object without any need to see the arrangement. But the issue is different with arrays since the index is in sequence.

const teamMembers = ["MATUMBAMAN", "Nisha", "zai", "YapzOr", "Puppey"];
Enter fullscreen mode Exit fullscreen mode

We will start from here.

Destructure in sequence

Since the array's index is in sequence, we need to follow the arrangement when destructuring. With that, -

const [core1, mid, core2, support1, support2] = teamMembers;

console.log(core1); // MATUMBAMAN
Enter fullscreen mode Exit fullscreen mode

So, you can see we destructure everything in the array. So, what if I only need the first 2? Well, just omit the rest!

const [core1, mid] = teamMembers;

console.log(mid); // Nisha
Enter fullscreen mode Exit fullscreen mode

Then, how about the last 2? Because we need to put it in sequence, right? Well, you can leave it blank of course!

const [ , , , support1, support2] = teamMembers;

console.log(support2); // Puppey
Enter fullscreen mode Exit fullscreen mode

Next! How about using a spread operator for the rest? Chill, we got this covered!

const [core1, mid, ...otherMembers] = teamMembers;

console.log(otherMembers);
// ["zai", "YapzOr", "Puppey"]
Enter fullscreen mode Exit fullscreen mode

The spread operators will take the rest, and pass it as a new array. The spread operator first and then destructure the last 2? Stop right there! I am afraid that that is not possible unless you need to use .split for that purpose.

What? Do you say you want to use the object way? Well, sure you can, but rename is compulsory then.

const {
  0: core1,
  1: mid,
} = teamMembers;

console.log(mid); // Nisha
Enter fullscreen mode Exit fullscreen mode

So, that means, we can do things like destructure the middle and spread operator for the rest? Well well well, that works like jolly!

const {
  2: core2,
  ...otherMembers
} = teamMembers;

console.log(core2); // zai
console.log(otherMembers);
// { 0: "MATUMBAMAN", 1: "Nisha", 3: "YapzOr", 4: "Puppey" }

// Note that `...otherMembers` will try to retain
// the index if destructure didn't happen at index 0,
// and will produce object instead.
Enter fullscreen mode Exit fullscreen mode

Conclusion

That is everything about destructuring! From objects to arrays, we learn how to extract entries inside objects and arrays, so it will be easier for us to call later on. Note that destructuring will create a new variable in place without changing the original object or array. This is cooler when is used with functions.

const displayName = ({ player, coach, director = "Luck" }) => {
  console.log(`Player is ${player}`);
  console.log(`Director is ${director}`);
};

displayName({ coach: "Master", player: "Atif", director: "Life" });
// Player is Atif
// Director is Life

displayName({ coach: "Master", player: "Aiman" });
// Player is Aiman
// Director is Luck

// Note that I put coach first instead of player. And it still works!
Enter fullscreen mode Exit fullscreen mode

In this way, you don't have to put the parameter in sequence anymore. Neat right?! And even, you can do default value, if the parameter is not passed!

So, thanks for the read, and until then, sayonara and peace be upon ya!

Top comments (5)

Collapse
 
janpauldahlke profile image
jan paul

good writeup man, ty. can you tell how to do this in typescript?

const { members: teamMembers } = team;

?

Collapse
 
alanxtreme profile image
Alan Daniel

Amazing, i'm already subscribed because i like how you teach, however i would really appreciate if you could show us how to do this with typescript.

Collapse
 
alserembani profile image
Atif Aiman

Sorry, quite busy with things right now. Will write it one day

Collapse
 
vit100 profile image
Vitaliy Markitanov

Object with 6 entries,

Typo? 7 entries.

Collapse
 
alserembani profile image
Atif Aiman

You caught the bug! πŸ›