How to exit from a function in JavaScript

How to exit from a function in JavaScript :

Exit from a function is required if you find that some condition doesn’t meet to run the full function and you want to get back to the caller function from the current point. In JavaScript, we don’t have any specific method that can be invoked to exit from the function.

The easiest way to do this by using return. If you use return, it returns undefined by default. You can also return a specific value if you want. Another way is to use throw if you have a try-catch block in the function.

In this post, I will show you two different examples on how to exit from a function early using return and throw.

Using return:

For the below program:

const getData = (num) => {
    if(num < 0){
        return;
    }

    return num%5;
}

const result = getData(-41);

console.log(result);

We are calling getData with a negative value. In getData, we are using return to exit from the function early if the argument is negative. If you run this program, it will print undefined.

Now, let’s take a look at the below program:

const getData = (num) => {
  if (num < 0) {
    return { success: false, result: 0 };
  }

  return { success: true, result: num % 5 };
};

const result = getData(-41);

console.log(result);

This time, we are returning one JSON object for early exit and for the result. For this example, it will exit early and print the below value:

{ success: false, result: 0 }

That means we can either use return without any value to return undefined or we can use return with a value to exit early from a function in JavaScript.

Using throw:

throw is used in a try-catch block to throw an exception. We can also throw one object from a function and receive it in the caller function. For example:

const getData = (num) => {
  if (num < 0) {
    throw { success: false, result: 0 };
  }

  return { success: true, result: num % 5 };
};

try{
    const result = getData(-41);
    console.log(result);
}catch(e){
    console.log(e)
}

In this example, we are throwing one JSON object from the function getData. We need to wrap getData calling part in a try-catch block to handle the data returned by throw. If you run this program, it will move to the catch block and print the value e i.e. the JSON object thrown from getData. It will print:

{ success: false, result: 0 }

This method is useful if you don’t want to check for the return value and directly wants to move to a different block in your code.

You might also like: