January 2024: How to Destructure Deeply Nested JavaScript Objects
And how to prevent them from throwing undefined errors in your code if those properties don't exist.
Hi friends,
Now that the holidays are behind us and we’re steaming ahead into 2024, I hope this email finds you well.
This monthly newsletter update will be a bit shorter than normal because although work’s kept me busy, I don’t really have anything tangible about it to share.
Briefly, I’ll say that we’re overhauling the authentication and authorization system which begins with understanding how the current system works, and building a proof of concept of how the new system could work. It’s been a lot of reading documentation, looking at other code examples, breaking down large chunks of functionality into smaller, easier-to-tackle stories, and hacking away at code as I figure things out. All absolutely necessary stuff, just not very exciting to talk about yet.
Instead, I’ll give you a quick read on how to destructure objects in JavaScript.
Destructuring simple objects with JavaScript’s ES6 syntax is pretty straightforward, but what about when your object has data nested two or even three layers deep. Can you handle that amount of curly braces?
I previously wrote about how ESLint’s unyielding rules helped me to write better code and be a better developer, but one error I kept running into was: Must use destructuring props assignment eslint(react/destructuring-assignment)
- especially in the context of complex object with many layers to them. Like this.props.match.params.username
- what a pain to have to keep typing (and ignorning the ESLint warning in my code editor).
For quite a while, I just disabled the error instead of fixing it, but one day I’d had enough, and I learned not only how to properly destructure such a deeply nested object, but also how to prevent my JavaScript code throwing undefined
errors if properties were missing via default values.
It wasn’t as bad as I thought it would be to fix, and I’m all the better for knowing how to do it the right way now.
I hope you enjoyed this month’s edition of “Paige Codes.” Please share with your friends if you did.
See you again at the end of February,
- Paige
Not subscribed yet? No worries.
I send a free email every month or so. You can check out my archive, or sign up below: