I have a function:
function myfunction() { if (a == 'stop') // How can I stop the function here? }
Is there something like exit()
in JavaScript?
Break is mostly used to exit from loops but can also be used to exit from functions by using labels within the 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.
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() .
To stop the execution of a function in JavaScript, use the clearTimeout() method. This function call clears any timer set by the setTimeout() functions.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With