477

I have a function:

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

Is there something like exit() in JavaScript?

Kara
  • 6,115
  • 16
  • 50
  • 57
Simon
  • 22,637
  • 36
  • 92
  • 121
  • 4
    do you want to stop the execution or return? – Ken Struys Jul 25 '10 at 17:20
  • @Ken Struys what is the difference? as i understand, if i make return, it stops the execution? isn't it? – Simon Jul 25 '10 at 17:23
  • 3
    Well here's the thing, using a return will just return to the context of the calling function. If you actually want the exit semantic you want to stop execution, you could do something like this: http://vikku.info/codesnippets/javascript/forcing-javascript-to-abort-stop-javascript-execution-at-any-time/ – Ken Struys Jul 25 '10 at 17:34
  • 1
    @Ken - That link you provided deals with stopping execution of a `for` loop. Even then, I have no idea why the method suggested would be used, when you could just call `break;`. To use the example from the article: `if(i==5) break;` Using `return` will halt the execution of the function, whether or not you're in a `for` loop. – user113716 Jul 25 '10 at 18:09
  • Syom - Yes, `return` will stop the execution of the function, which seems to be what you asked. – user113716 Jul 25 '10 at 18:11
  • @patrick yes that example is for iteration but the behavior of javascript_abort is very different from a break, or a return. Here's a better example: function a() { b(); alert("wont execute"); } function b() { if(true) { alert('going to abort'); javascript_abort(); } } function javascript_abort() { throw new Error('This is not an error. This is just to abort javascript'); } a(); Note that if you used a return the second alert would be called. I'm not advocated this as a good solution it's just a way to get a exit like behavior. – Ken Struys Jul 25 '10 at 19:53

12 Answers12

747

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;
user113716
  • 318,772
  • 63
  • 451
  • 440
  • 6
    I know this is an old post, and this is common practice BUT I think this is a bad solution. If the function is SUPPOSED to return a value, you should use return. If you just blindly use return you might run into problems later. Especially if you start binding events that have a return in them. Check out this post for more info: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/ –  Jul 14 '11 at 21:53
  • 83
    @dbme: Functions in JavaScript *always* return. The return statement is implicit if it hasn't been provided. The default return value is `undefined`, and that's what my primary solution provides. The article you referenced is talking about doing `return false` in a jQuery event handler. That's an entirely different issue. This is the proper way to exit a JavaScript function. Obviously if the caller relies on the value returned, the value needs to be defined appropriately. – user113716 Jul 14 '11 at 22:03
  • 3
    ...An implicit variation would be `if(a != 'stop') { /* run my code */ }` so that the code only runs when `a` doesn't equal `'stop'` without providing an explicit `return`. But the return value *is identical to my solution*. In both cases, `undefined` will be returned. – user113716 Jul 14 '11 at 22:06
  • 4
    Awesome response. I didn't realize there was any difference between returning undefined vs false vs a different value. I've been trying to find a definitive answer regarding this behavior for the past hour. So is it safe to say (to reiterate your point) that return is a 100% safe way to exit a method, even if the caller is bound to events etc? –  Jul 14 '11 at 22:11
  • @dbme: Well, it all depends on what is expected by the method calling the function. If some code library defines an event system that will break if it receives `undefined` (or it doesn't receive some other value) as a return value, then you'll need to conform to the specification of that API, and return the correct value. Generally for an event handling system, it will expect `undefined` as a simple indication that the handler has finished, and there are no further instructions. With jQuery, `return false;` has special meaning giving instruction to do a `preventDefault` and `stopPropagation`. – user113716 Jul 14 '11 at 22:19
  • Again, awesome response. And for those like me who had no real idea how to use return properly, here's a test case: http://jsfiddle.net/GpEtq/ Works perfectly. Thanks @patrick-dw –  Jul 14 '11 at 22:27
  • Even though you could rely on impicit `undefined` return or explicit (`return;`) , you should always return something "readable" when you evaluate function's return value - someday someone might want that, however if you make a "procedure" (where return value is not evaluated) - there is no need for that :) – jave.web May 12 '15 at 06:44
  • This solution actually doesn't always work. Here's a use case where it doesn't `const func = function(){ ["item1", "item2", "item3"].forEach(item => { if (item === "item1"){ checker = true return item } }) if(checker){ console.log("This should not print") } return undefined } console.log(func())` You can put that in a file like `test.js` and then run `node test.js` to see what happens. – Sam Jun 29 '20 at 22:18
  • Disregard my last comment, I forgot that I was using a nested inline function, and that the return would be returning from the inline function – Sam Jun 29 '20 at 22:20
58

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

Community
  • 1
  • 1
CMCDragonkai
  • 6,222
  • 12
  • 56
  • 98
  • is it possible to use this solution with nodejs exports module? when I try it I get "not used label" error. exports.MyFunction = function(data){myFunction:{break myFunction;}} – Yuri Almeida Feb 01 '17 at 16:12
24
function myfunction() {
     if(a == 'stop') 
         return false;
}

return false; is much better than just return;

user664833
  • 18,397
  • 19
  • 91
  • 140
xlaok
  • 587
  • 5
  • 11
  • 22
    Why is `false` better? I'd say the default `undefined` is better in the generic case. Either way, you're correct to say it's often better to return a meaningful value. – Brad Koch Apr 30 '13 at 15:06
  • 1
    It's up to the programmer and dependant on the use case. For example, a function might validate something, so if the validation fails it makes more sense to return `false` than `undefined`. – Adam McArthur Oct 01 '14 at 04:06
17

This:

function myfunction()
{
     if (a == 'stop')  // How can I stop working of function here?
     {
         return;
     }
}
Rob
  • 45,296
  • 24
  • 122
  • 150
13

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
    }
}
Rodney Salcedo
  • 1,228
  • 19
  • 23
  • This is probably the only way to actually stop execution. However, I do think the original poster is speaking about returning from a function early. (Someone made a 1 minute youtube video on this that I just found, haha [break out](https://www.youtube.com/watch?v=9U0vmbNy128). After all, you can technically decide to throw an exception based on return value in the outside scope. (Which in my opinion would have been more proper logically.) – InfiniteStack Mar 29 '21 at 16:56
  • It is a bad practice to control flows with exceptions. More details https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why – T04435 Oct 27 '22 at 03:58
3

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.

2

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 */
    }
}
4castle
  • 32,613
  • 11
  • 69
  • 106
Seize
  • 59
  • 7
1

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.

Bedram Tamang
  • 3,748
  • 31
  • 27
  • But the function keeps executing after I throw an error. – Abdulhakim Zeinu Jul 14 '21 at 15:17
  • 1
    No `throw new Error()` is used when really some thing went wrong. If you want to exit function use `return true/false`. Big applications are saving errors and it will be sad if it will log thousand of errors from correct working code. – Mises Sep 17 '21 at 06:32
0

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.

Leo
  • 2,331
  • 2
  • 19
  • 17
-4

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();
       ................
  }
silvster27
  • 1,916
  • 6
  • 30
  • 44
  • 8
    `stopImmediatePropagation()` is not a jQuery thing, and stopping propagation is not the same thing as exiting a function. – Brad Koch Apr 30 '13 at 15:01
-5

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

-22

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

exit

or

die:-)
amrali
  • 3
  • This may stop all code from being executed, not only the rest of the function. Check fiddle: https://jsfiddle.net/b3k0xo7n/1/ – treecon Jun 19 '17 at 21:13
  • 3
    What a terrible programming approach. How is this intuitive for another developer who works on the same codebase? – osullic Jun 26 '18 at 15:07