70

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
  • 30,952
  • 84
  • 245
  • 427

6 Answers6

125
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
  • 58,730
  • 15
  • 91
  • 116
18

Use return statement anywhere you want to exit from function.

if(somecondtion)
   return;

if(somecondtion)
   return false;
Adil
  • 146,340
  • 25
  • 209
  • 204
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
  • 86,271
  • 21
  • 138
  • 164
5

Use this when if satisfies

do

return true;
Sam Arul Raj T
  • 1,752
  • 17
  • 23
3

You should use return as in:

function refreshGrid(entity) {
  var store = window.localStorage;
  var partitionKey;
  if (exit) {
    return;
  }
Yosep Kim
  • 2,931
  • 22
  • 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,281
  • 16
  • 26