Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Early exit from function?

Tags:

javascript

I have a function:

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

Is there something like exit() in JavaScript?

like image 438
Simon Avatar asked Jul 25 '10 17:07

Simon


People also ask

Can Break exit a function?

Break is mostly used to exit from loops but can also be used to exit from functions by using labels within the function.

Does return exit out of function?

The return statement terminates the execution of function and it returns the control to the calling function. It calls the constructor as well as the destructor.

How do you terminate a function?

The terminate() function calls the function pointed to by terminate_handler . By default, terminate_handler points to the function abort() , which exits from the program. You can replace the default value of terminate_handler with the function set_terminate() .

How do I stop a JavaScript function from running?

To stop the execution of a function in JavaScript, use the clearTimeout() method. This function call clears any timer set by the setTimeout() functions.


2 Answers

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; 
like image 59
user113716 Avatar answered Oct 13 '22 09:10

user113716


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

like image 20
CMCDragonkai Avatar answered Oct 13 '22 11:10

CMCDragonkai