This page looks best with JavaScript enabled

Quick Tips - Early Returns

 ·  ☕ 1 min read

    A good tip to keep in mind when programming is minimizing your use of else statements. When possible, exit the function context earlier given a value that establishes the given return, rather than reflecting that with an else statement to check for something else. That may sound complicated, but its not, here is an example:

    Do This

    1
    2
    3
    4
    5
    6
    
    function thing(args) {
    	if(!args.required_thing) {
    		throw 'missing required thing';
    	}
    	// do something + return, or return
    }
    

    Not This

    1
    2
    3
    4
    5
    6
    7
    8
    
    function thing(args) {
    	if(args.required_thing) {
    		// do something + return, or return
    
    	} else {
    		throw 'missing required thing';
    	}
    }
    

    Figure 1 uses the end of the function to assume a positive result, exiting if this is not met as early as possible. This is pretty much always going to be preferred to Figure 2.

    Share on

    abschill
    WRITTEN BY
    abschill
    software engineer