How can I exit from a javascript function?

JavascriptJquery

Javascript 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.

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
QuestionSamantha J T StarView Question on Stackoverflow
Solution 1 - JavascriptFlorian MargaineView Answer on Stackoverflow
Solution 2 - JavascriptAdilView Answer on Stackoverflow
Solution 3 - JavascriptthecodeparadoxView Answer on Stackoverflow
Solution 4 - JavascriptSam Arul Raj TView Answer on Stackoverflow
Solution 5 - JavascriptYosep KimView Answer on Stackoverflow
Solution 6 - JavascriptRodrigo E. PrincipeView Answer on Stackoverflow