How to Exit From JavaScript Function

Published on January 5, 2020 22 sec read

In this guide, I’ll show how to exit from a JavaScript function.

Structure

Let’s see the structure:

if ( condition ) {
    return;
}

The return exits the function by returning undefined.

We can also exit the function by returning false:

if ( condition ) {
    return false;
}

At this time, the return exits the function by returning false.

An Example

I’m creating a function to do the sum of two numbers. We want to exit the function if the number/s not given.

function sum(a,b){

	  // exit
    if(!a || !b ){
        return;
    }

   return a + b;
}

console.log(sum()); // undefined
console.log(sum(5)); // undefined
console.log(sum(5,5)); // 10

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *