Write cleaner code using these destructuring patterns
Knowing how destructuring works is not the same as knowing how to use it, however. Here are three destructuring patterns you can use to make your code cleaner, more robust, and more readable!
1. Named Function Arguments
Named arguments are an alternative way to handle function parameters rather than by position. Instead of ordering your arguments in the same order as the function signature, you simply specify the argument by name. For example, in Python:
As you can see, the order of the arguments does not matter — you just specify them by name. The benefits of named arguments vs. positional are:
- You can leave off one or more parameters when calling the function
- Order does not matter when passing in arguments.
- More readable code when calling a function that might exist elsewhere
This patterns hits all of our goals for named arguments. We were able to leave off the argument
c, the order does not matter, and we assign our argument by referencing them by name. This is all made possible by object destructuring.
2. Cleanly Parse a Server Response
Often we only care about the data block or even one specific value in the data block of a server response. If that is the case, you can use destructuring to only grab that value while ignoring a lot of the other things a server typically sends back. Here is an example:
This pattern allows you to pull out values from an object as your arguments are being parsed. You also get to set up defaults for free! Which brings us to the third pattern…
3. Setting Default Values During Assignment
A common case when assigning variables or constants is to have a default value if some other value doesn’t currently exist in the scope.
Prior to destructuring, you could do something like this to achieve that desired behavior:
// old way of setting up default values
var nightMode = userSettings.nightMode || false
But this requires an individual line of code for each assignment. With destructuring, you can take care of all of your assignments and their defaults all at once:
This destructuring pattern can be applied to setting up state in your React components!
I hope you are able to apply some of these patterns to your code! Check out the links below to learn more about destructuring.