69

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?

Samantha J T Star
  • 28,982
  • 82
  • 233
  • 406

6 Answers6

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

Florian Margaine
  • 54,552
  • 14
  • 89
  • 116
18

Use return statement anywhere you want to exit from function.

if(somecondtion)
   return;

if(somecondtion)
   return false;
Adil
  • 143,427
  • 25
  • 201
  • 198
7

you can use

return false; or return; within your condition.

function refreshGrid(entity) {
    var store = window.localStorage;
    var partitionKey;
    ....
    if(some_condition) {
      return false;
    }
}
thecodeparadox
  • 84,459
  • 21
  • 136
  • 161
5

Use this when if satisfies

do

return true;
Sam Arul Raj T
  • 1,712
  • 16
  • 21
3

You should use return as in:

function refreshGrid(entity) {
  var store = window.localStorage;
  var partitionKey;
  if (exit) {
    return;
  }
Yosep Kim
  • 2,853
  • 20
  • 23
2

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.

Rodrigo E. Principe
  • 1,213
  • 16
  • 23