Javacript techniques: Fallbacks when destructuring nullable objects

Search for a command to run...

Just simple and straight forward. I'm sharing this immediately. Keep up the good work man. 🔥🔥🚀
Automating the boring stuff in job applications, while keeping the final decision in your hands.

Automating the boring stuffs ...

Managing S3 Case Sensitivity in Python Workflows

🌩️ Cloud computing has revolutionized how applications are developed and deployed, providing a more flexible and scalable environment for running workloads. AWS offers several services for event-driven computing, including Amazon CloudWatch Events a...

Introduction📝 Looking to streamline your complex workflows and keep everything on track? Look no further than state machines - a powerful tool for precision and ease in process management. 💪🏼 And when it comes to implementing state machines, AWS S...

JavaScript is a loosely typed language and thus your programs are prone to runtime errors. A runtime error is an error that occurs during the execution of the program, also known as the exceptions. In the example that is given below the program is syntactically correct , but at runtime it is trying to destructure a null object and throws an Error! ☹.
let {name, age, favColour} = player1;
// where player1 could be null
If we must do conditional destructuring and assignment with null-checks, then we might need to write-up boilerplate code to reduce the frequency of this kind of errors.
Let's see an example:
This code snippet checks if a variable is defined before assigning it to a class property . it thus prevent errors
if (file == undefined) {file = false} //prevents errors
if (file) {
this.file = file
}
So this happened to me a while back. It took me a while to debug my code and find the culprit 😈 . Then I figured I returned a promise that made a function call and the data that was being passed was undefined 🤦♂️. So whenever you write a function that performs destructuring assignment. RULE OF THUMB; I mean always make sure you set a fallback and error checkers.
You can use an empty object as fallback, and if object is null or undefined the assigned variables will be undefined.
Sample code snippet employing "empty object" as a fallback strategy
function printAge(player1 = {}) {
const { age } = player1;
}
printAge(); // ✅ , no errors 👌
Another implementation of "empty object" as a fallback strategy
const player1 = null;
const { age, name, favColor } = player1 || {};
console.log(age, name, favColor);
Thanks guys for the audience 🤓! Connect with me on Twitter, linkedIn and Github And do drop your comments and reviews.