One reason to exit a function can be considered a “job done” situation. The return statement immediately exits the function, and any value or variable passed after return will be returned. This is a common way to exit a function based on a certain condition or conditions.
Here's an example of using the return statement to exit a function:
In other words, return terminates the function and returns a value.
Below is an example. Let us suppose we are on the hunt for prime numbers. Let us further assume we are starting from 90. As soon as we find a prime, we can exit a function (and we will use “break” to illustrate it). Here is our program:
Note that we define a function called checkPrime and within this function, we are iterating through numbers from 90 to 120 using a for loop. For each number, we check if it is a prime number by iterating from 2 to the number itself minus 1. If the number is not prime, it is displayed on the document.
The program does not use an efficient algorithm to check for prime numbers, but we are using it here to illustrate the idea of exiting a function as soon as we know we don’t need to search anymore.
The output of this program is:
In other words, all numbers from 90 to 96 (inclusive) are composite. 97 is prime and as soon as we know this we break from the program and thus exit the function.
In this example, a for loop is used to iterate from 0 to 4. Inside the loop, there's an if statement that checks if the current value of i is 3. If it is, an error is thrown. This will cause the loop to be exited, and the error will be propagated up the call stack. Essentially, the console.log() will be skipped (for the value of 3 and for the value of 4 as well because the program has exited).
Thus the console.log() output will look something like:
Thus in summary, you use return for “job done”, break for “not necessary to do any work anymore” and throw for “something bad or unexpected happened, I need to exit”.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.