0

# Early Exit From Functions Ok! It's crucial to keep the code readable and maintainable. One of the easiest ways to increase readability is terminating early from methods/functions.

Let's consider the following code:

``````function sum(n1: number, n2: number) {
if(  typeof n1 === 'number' && typeof n2 === 'number'){
// do stuff
const result = n1 + n2;
console.log(result);
return result;
} else {
throw new Error('Argument is not a number');
}
}
``````

This can easily be written as:

``````
function sum(n1: number, n2: number){
if(typeof n1 !== 'number') throw new Error('n1 is not a number');
if(typeof n2 !== 'number') throw new Error('n2 is not a number');

// we are safe to do stuff!
const result = n1 + n2;
console.log(result);
return result;
}``````

We have eliminated the `else` block and immediately the structure got leaner.

Obviously, we don't need to throw errors, we can also exit the function simply by returning if the returned value makes sense for your business use case. (The following is not a super good example but I will keep it to be consistent with the function above).

``````function sum(n1: number, n2: number){
if(  typeof n1 !== 'number'
|| typeof n2 !== 'number') return 0;

// we are safe to do stuff!
const result = n1 + n2;
return result;
}``````

We have somewhat have this practice for callback functions.

``````function someMethod(callback: Function){
someCall((err, data)=>{
if(err){ // if error, don't do anything further
return callback(err);
}

// do stuff
return callback(null, data);
});
}``````

The structure looks a lot simpler when we put the exits on top. If the exit logics are getting mixed and complicated that might be a good sign to split up the function to smaller functions.

One last example is good old recursive functions. Whenever we start writing a recursive function, we start with the exit logic.

``````function factorial(x: number){
if(x<=1) return 1;

return x * factorial(x-1);
}

console.log(factorial(5));``````

Conclusion

Exiting a function early almost always makes the function more readable. Otherwise, the core logic gets mixed with the checks we do to cover unwanted scenarios. This will result in more complicated flows.                 Join Hacker Noon