mardi 30 novembre 2021

How to write cleaner if-else statements and prevent nesting

So I know that nesting code can get ugly very quickly. Therfore I looked up a way to prevent nesting an found out that you can do the following

if (user == null) return;

console.log('Deleting');
user.delete();

Instead of using curly brackezs like that

if (user != null) {
console.log('Deleting');
user.delete();
}

However I can't really see how this is helpful when using an if-else statement. For example: I have this piece of code from my project that I would really like to write in a cleaner way than that. But I am struggling to figure out how this can be done.

               if (parseInt(year) == joinTime.getFullYear()) {
                    if (parseInt(month) == joinTime.getMonth() + 1) {
                        if (parseInt(day) == joinTime.getDay()) {
                            channel.send(message);
                        } else {
                            comparison(day, hour, minute);
                        }
                    } else {
                        comparison(day, hour, minute);
                    }
                } else {
                    comparison(day, hour, minute);
                }

Aucun commentaire:

Enregistrer un commentaire