Early exit from function?

Javascript

Javascript Problem Overview


I have a function:

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

Is there something like exit() in JavaScript?

Javascript Solutions


Solution 1 - Javascript

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;

Solution 2 - Javascript

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: https://stackoverflow.com/questions/1361437/javascript-equivalent-of-phps-die

Solution 3 - Javascript

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

return false; is much better than just return;

Solution 4 - Javascript

This:

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

Solution 5 - Javascript

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
	}
}

Solution 6 - Javascript

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.

Solution 7 - Javascript

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 */
    }
}

Solution 8 - Javascript

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.

Solution 9 - Javascript

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.

Solution 10 - Javascript

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();
       ................
  }

Solution 11 - Javascript

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

Solution 12 - Javascript

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

exit

or

die:-)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimonView Question on Stackoverflow
Solution 1 - Javascriptuser113716View Answer on Stackoverflow
Solution 2 - JavascriptCMCDragonkaiView Answer on Stackoverflow
Solution 3 - JavascriptxlaokView Answer on Stackoverflow
Solution 4 - JavascriptRobView Answer on Stackoverflow
Solution 5 - JavascriptRodney SalcedoView Answer on Stackoverflow
Solution 6 - JavascriptAwal IstirdjaView Answer on Stackoverflow
Solution 7 - JavascriptSeizeView Answer on Stackoverflow
Solution 8 - JavascriptBedram TamangView Answer on Stackoverflow
Solution 9 - JavascriptLeoView Answer on Stackoverflow
Solution 10 - Javascriptsilvster27View Answer on Stackoverflow
Solution 11 - JavascriptChirag Dineshbhai PondaView Answer on Stackoverflow
Solution 12 - JavascriptamraliView Answer on Stackoverflow