Multiple return statements in Javscript Functions

Hello,

in the course Javascript - Chapter Functions. The return statement is discussed.

function rectangleArea(width, height) {
  if (width < 0 || height < 0) {
    return 'You need positive integers to calculate area!';
  }
  return width * height;
}

But for me it is not clear and not good explained. Is that even possible, that you have multiple return statements?

Hi and welcome to the forums!

You can indeed have multiple return statements in a function, however only one will run during any single function call. This can be useful for if you want to exit the function early if the inputs do not meet the requirements for example, such as the function you posted. It’s unclear the benefit in that function, but imagine your function involved a loop or a recursive call, such as this:

function printNumbers(maxNumber) { for (let i = 1; i <= maxNumber; i++) { console.log(i); } return 0; } printNumbers(200); // prints the numbers 1-200

Here we can see that we have a loop running based on the input given. However we can spot a couple possibly problems already. For example what if the user doesn’t input a number? The code won’t work! Therefore rather than having errors in the program we can handle this using a return at the beginning:

function printNumbers(maxNumber) { if (!Number.isInteger(maxNumber)) return "Not an integer!" for (let i = 1; i <= maxNumber; i++) { console.log(i); } return 0; } console.log(printNumbers("200")); // prints the numbers 1-200

However, this function also has the issue of running whatever number we want. The user could put in an exceptionally high number and crash the program. Therefore we can put a max cap on the size of the input like so:

function printNumbers(maxNumber) { if (maxNumber > 10000) return "Number too large!" if (!Number.isInteger(maxNumber)) return "Not an integer!" for (let i = 1; i <= maxNumber; i++) { console.log(i); } return 0; } console.log(printNumbers(100000000000000000000000000000000000000000)); // prints the numbers 1-200

This lets us escape from the function before it runs the code, which could take a while if you have a large number in your loop.

Worth noting that this use of return is actually quite hotly debated. Some people think that you should only ever have one return statement per function and use if conditions, others think you should use these returns to exit the function early when needed. However hopefully this at least explains why you can use multiple returns, it’s use cases and you can then decide whether or not this is something you’d like to use!