DEV Community

Cover image for Object Destructuring - but why?
Christian Kozalla
Christian Kozalla

Posted on • Originally published at chrisko.io

Object Destructuring - but why?

Once you have learnt a little bit of JavaScript, you may have come across a concept called Object Destructuring.

When I first read the term I thought: "What the heck is this?" 😕

Destructuring allows you to unpack key/value pairs from objects and store each in it's own variable. 👍

Note: Destructuring is possible with arrays as well, which obviously have no key/value pairs, but essentially are also a JavaScript object. 😉

So what exactly does unpacking an object mean ❓

Consider the following lines of code:

const payload = {
  key: "myKey",
  name: "Christian",
  age: 27,
  married: true,
  occupation: "developer"
};

const validate = (payload) => {
  // validate payload
  if (
    payload.key &&
    payload.name &&
    payload.age &&
    payload.occupation &&
    payload.hasOwnProperty("married")
  ) {
    console.log("All fields are set");
  } else {
    console.log("Please fill out the form properly");
  }
};
Enter fullscreen mode Exit fullscreen mode

Imagine you have some kind of form <input /> on an app, that stores the values in component state on the client-side. Once the user presses the Upload button, a validation function might be called to highlight form fields that are not filled out correctly. Now, our form data is stored in an object payload that we pass to the validation function validate(payload).

The function wants to check if our object keys contain truthy values. That's what we do in the if statement's condition.

This is a darn long line of code - it's been a hassle to write and sure is a pain to read! 😡

Now, imagine you would have to reference and check these keys more often throughout the function code!

❤️ Object Destructuring to the rescure - reduces risk of typos, improves readability.

const payload = {
  key: "myKey",
  name: "Christian",
  age: 27,
  married: true, // test with false, null, undefined
  occupation: "developer"
};

const validate = (payload) => {
  // destructure payload - unpacking...
  const { key, name, age, married, occupation } = payload;

  // Now we can access these keys as ordinary JavaScript variables
  if (key && name && age && occupation && typeof married === "boolean") {
    console.log("All fields are set", key, name, age, occupation, married);
  } else {
    console.log("Please fill out the form properly");
  }
};

validate(payload);
Enter fullscreen mode Exit fullscreen mode

Here, first thing we do is destructuring the payload keys into their own variables.

// destructure payload - unpacking...
const { key, name, age, married, occupation } = payload;
Enter fullscreen mode Exit fullscreen mode

You often saw this line in the ol' days when React components were still JavaScript classes, instead of functions. So, in order to access the keys of an object passed as props to the class component, the first line inside the render() function would destructure the keys from the props:

// Destructuring inside the render function
// of a React class component
render() {
  const { name, age } = this.props;
  return {
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  }
}
Enter fullscreen mode Exit fullscreen mode

Object destructuring in the function definition

Most confusing is the syntax of a destructuring assignment inside the parameters of a function definition:

const myFunc = ({ name, age, occupation }) => {};
Enter fullscreen mode Exit fullscreen mode

In the definition of myFunc the parameters are already destructured!

See, it is clear that an object is passed to the function with the following keys: name, age and occupation

So, here is the most concise version of our first example code with destructuring inside the function definition:

const payload = {
  key: "myKey",
  name: "Christian",
  age: 27,
  married: true, // test with false, null, undefined
  occupation: "developer"
};

const validate = ({ key, name, age, married, occupation }) => {
  // Now we are saving one line,
  // because destructuring inside the function definition
  if (key && name && age && occupation && typeof married === "boolean") {
    console.log("All fields are set", key, name, age, occupation, married);
  } else {
    console.log("Please fill out the form properly");
  }
};

validate(payload);
Enter fullscreen mode Exit fullscreen mode

Object destructuring is nice, but when to use it?

First off: You don't have to use object destructuring.

You might need to be familiar with the object destructuring when reading other people's code.

But apart from that, object destructuring is nice to know and might be a handy concept of writing code a little cleaner.

I have been familiar with the concept of destructuring for a little while now, but never used it in a regular basis.

But recently, I used it in a project with Vue and Vuex. I dealt with a bunch of arguments I wanted to pass to a Vuex action, which would perform some tasks on the arguments and then call a Vuex mutation to update the state, if processing went fine.

So first I had to pass everything like 4 - 5 key/value pairs to the action, then write the code for the action, then pass everything or a subset of arguments to the mutation handler.

Without destructuring my function arguments both for the Vuex action and mutation I totally lost track of all the stuff being passed in and out of the functions! 😕

With object destructuring right in the function definition, I easily remembered how I named the parameters passed at different places throughout the app! 👍

Conclusion

To sum up, object destructuring is great for writing readable code. I find it especially useful inside a function definition in order to keep track of all the parameters passed to the function.

Stay tuned && happy coding! 🚀

If you liked this post or have any feedback whats-o-ever, I'd be grateful if you'd jot down your thoughts below! Thanks for reading! ❤️

Top comments (7)

Collapse
 
sahilsaif1221 profile image
Sahil Saif

Today i was learning destructuring and was lit bit confuse of it's uses , and why need to use it. you give a well clear idea about it. Now it is very much clear in my mind about it's uses. so Thanks mate!

Collapse
 
christiankozalla profile image
Christian Kozalla

You're welcome! I am glad you found it useful

Collapse
 
andrewbaisden profile image
Andrew Baisden • Edited

Object destructuring is so good I use when I can.

Collapse
 
lyrod profile image
Lyrod

You could talk about default value as well 😁

Collapse
 
christiankozalla profile image
Christian Kozalla

Sure, default parameters work with object destructuring as well!

If the object passed to myFunc has no name property, the default value "Unknown" will be logged (instead of undefined) 👍

const myFunc = ({ name = "Unknown", age }) => {
  console.log(name, age);
};
Enter fullscreen mode Exit fullscreen mode

Thanks for your suggestion, I'll update the post!

Collapse
 
tanth1993 profile image
tanth1993

object destructuring is useful. However, you should not use with methods(function in Object) because it will loose context of this

Collapse
 
christiankozalla profile image
Christian Kozalla

Thanks for the heads up!