Object Destructuring - but why?
Christian Kozalla
Posted on April 4, 2021
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");
}
};
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);
Here, first thing we do is destructuring the payload keys into their own variables.
// destructure payload - unpacking...
const { key, name, age, married, occupation } = payload;
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>
}
}
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 }) => {};
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);
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! ❤️
Posted on April 4, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 25, 2024