Simon
Simon

Reputation: 23149

Early exit from function?

I have a function:

function myfunction() {
  if (a == 'stop')  // How can I stop the function here?
}

Is there something like exit() in JavaScript?

Upvotes: 487

Views: 1067120

Answers (12)

Bedram Tamang
Bedram Tamang

Reputation: 4414

I think throw a new error is good approach to stop execution rather than just return or return false. For ex. I am validating a number of files that I only allow max five files for upload in separate function.

validateMaxNumber: function(length) {
   if (5 >= length) {
        // Continue execution
   }
   // Flash error message and stop execution
   // Can't stop execution by return or return false statement; 
   let message = "No more than " + this.maxNumber + " File is allowed";
   throw new Error(message);
}

But I am calling this function from main flow function as

  handleFilesUpload() {
      let files =  document.getElementById("myFile").files;
      this.validateMaxNumber(files.length);
}

In the above example I can't stop execution unless I throw new Error.Just return or return false only works if you are in main function of execution otherwise it doesn't work.

Upvotes: 2

xlaok
xlaok

Reputation: 597

function myfunction() {
     if(a == 'stop') 
         return false;
}

return false; is much better than just return;

Upvotes: 25

Leo
Leo

Reputation: 2326

I dislike answering things that aren't a real solution...

...but when I encountered this same problem, I made below workaround:

function doThis() {
  var err=0
  if (cond1) { alert('ret1'); err=1; }
  if (cond2) { alert('ret2'); err=1; }
  if (cond3) { alert('ret3'); err=1; }
  if (err < 1) {
    // do the rest (or have it skipped)
  }
}

Hope it can be useful for anyone.

Upvotes: -1

amrali
amrali

Reputation: 3

type any random command that throws an error, for example:

exit

or

die:-)

Upvotes: -22

exit(); can be use to go for the next validation.

Upvotes: -5

Seize
Seize

Reputation: 57

Using a return will stop the function and return undefined, or the value that you specify with the return command.

function myfunction(){
    if(a=="stop"){
        //return undefined;
        return; /** Or return "Hello" or any other value */
    }
}

Upvotes: 1

Rodney Salcedo
Rodney Salcedo

Reputation: 1254

Using a little different approach, you can use try catch, with throw statement.

function name() {
    try {
        ...

        //get out of here
        if (a == 'stop')
            throw "exit";

        ...
    } catch (e) {
        // TODO: handle exception
    }
}

Upvotes: 14

CMCDragonkai
CMCDragonkai

Reputation: 6382

Apparently you can do this:

function myFunction() {myFunction:{
    console.log('i get executed');
    break myFunction;
    console.log('i do not get executed');
}}

See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

I can't see any downsides yet. But it doesn't seem like a common use.

Derived this answer: JavaScript equivalent of PHP’s die

Upvotes: 58

silvster27
silvster27

Reputation: 1936

If you are using jquery. This should stop the function from bubbling up to so the parent function calling this should stop as well.

  function myfunction(e)
  {
       e.stopImmediatePropagation();
       ................
  }

Upvotes: -4

Awal Istirdja
Awal Istirdja

Reputation: 47

if you are looking for a script to avoid submitting form when some errors found, this method should work

function verifyData(){
     if (document.MyForm.FormInput.value.length == "") {
          alert("Write something!");
     }
     else {
          document.MyForm.submit();
     }
}

change the Submit Button type to "button"

<input value="Save" type="button" onClick="verifyData()">

hope this help.

Upvotes: 3

user113716
user113716

Reputation: 322592

You can just use return.

function myfunction() {
     if(a == 'stop') 
         return;
}

This will send a return value of undefined to whatever called the function.

var x = myfunction();

console.log( x );  // console shows undefined

Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.

return false;
return true;
return "some string";
return 12345;

Upvotes: 755

Rob
Rob

Reputation: 45789

This:

function myfunction()
{
     if (a == 'stop')  // How can I stop working of function here?
     {
         return;
     }
}

Upvotes: 17

Related Questions