How can I exit from a javascript function?
JavascriptJqueryJavascript Problem Overview
I have the following:
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
...
...
I would like to exit from this function if an "if" condition is met. How can I exit? Can I just say break, exit or return?
Javascript Solutions
Solution 1 - Javascript
if ( condition ) {
return;
}
The return
exits the function returning undefined
.
The exit
statement doesn't exist in javascript.
The break
statement allows you to exit a loop, not a function. For example:
var i = 0;
while ( i < 10 ) {
i++;
if ( i === 5 ) {
break;
}
}
This also works with the for
and the switch
loops.
Solution 2 - Javascript
Use return statement anywhere you want to exit from function.
if(somecondtion)
return;
if(somecondtion)
return false;
Solution 3 - Javascript
you can use
return false;
or return;
within your condition.
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
....
if(some_condition) {
return false;
}
}
Solution 4 - Javascript
Use this when if satisfies
do
return true;
Solution 5 - Javascript
You should use return as in:
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (exit) {
return;
}
Solution 6 - Javascript
I had the same problem in Google App Scripts, and solved it like the rest said, but with a little more..
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (condition) {
return Browser.msgBox("something");
}
}
This way you not only exit the function, but show a message saying why it stopped. Hope it helps.