Search code examples
javascriptif-statementnestedconditional-statementscoding-style

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 brackets 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);
            }

Solution

  • Style is in the eye of the beholder, but assuming you want cleaner code then something like this is what I would do:

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

    Alternatively, if you don't care about the additional return (and it doesn't break your logic):

    
        const yearMatch = (parseInt(year) == joinTime.getFullYear());
        const monthMatch = (parseInt(month) == joinTime.getMonth() + 1);
        const dayMatch = (parseInt(day) == joinTime.getDay());
    
        if (yearMatch && monthMatch && dayMatch) return channel.send(message);
        
        comparison(day, hour, minute);
    
    

    Of course, do change the variable names as appropriate.