DEV Community

David Ortega
David Ortega

Posted on

Better conditions: Invert your conditionals to beautify code

Do you get confused when it's been a week since you last checked code you wrote and now you can't understand the conditions in it? Do you have 2+ nested conditionals? Are If Else conditions your favourite ones? In this article we'll go through a short example on why you should invert your conditionals when doing checks on functions, remove else statements and how they make reading code easier.

Use conditionals at the beginning of your functions and return early

When writting a function, execution should stop as early as possible when a condition is not meet:

// โŒ Don't do this! 
// Execution does not stop until the end, we have to go
// through all the code to understand why 
// it does not work as expected
function execute() {
    if (isAllowed) {
        doSuccess();
    } else {
      doError();
    }
}

// โœ… Do this instead. If condition is not meet, return early
// Otherwise, continue with execution
function execute() {
    if (!isAllowed) {
        doError();
        return;
    }

    doSuccess();
}
Enter fullscreen mode Exit fullscreen mode

With this example, we have removed an else statement and made the code easier to read. If condition is not meet, return error. Otherwise, keep going.

Help the author

As this is my first post on the platform, I'd like to know your opinion on which language should I use for the example (maybe multiple ones?), and also if you would like more in-depth examples instead of a short one.

Thanks a lot for reading, read you in the comments!

Top comments (0)