Introduction
In computer programming, a function is a subroutine or a procedure that its name can call. Functions can be defined in many ways, but in most programming languages, a function is defined by a function header and a function body.
What is a return statement?
In programming, a return statement causes the function in which it is executed to stop running and return a value to the caller. A function can only have one return statement. If more than one return statement appears in a function, only the first one will be executed.
How many return statements should a function have?
The answer to this question depends on what the function is supposed to do. A function can have zero or more return statements. However, it is generally a good idea to have at least one return statement in a function so that the function can return something to the caller.
The single exit point principle
Functions should have a single point of exit at the end. Anything before that is an early return. That doesn’t mean functions can only have one return statement. They can have several, but only one at the end of the function.
If a function does need to return multiple values, it’s best to use an object or array which can hold all the values. That way the function has a single point of exit and is easier to reason about.
When to use multiple return statements
A function can have multiple return statements. However, it’s generally best to use just one return statement per function.
There are a few situations where multiple return statements can be useful:
- You want to return different values based on different conditions.
- You want to exit a function early (before reaching the end).
- You want to return multiple values from a single function. Let’s take a look at each of these situations in more detail.
Conclusion
There can be more than one return statement in a function, but they must be reachable. That is, you can’t put a return statement in the middle of an if-else chain if it’s not reachable by all code paths.