frenchie
frenchie

Reputation: 51927

javascript exiting function

I have a function that looks like this:

function MyFunction() {

  //do some work

  if (SomeCondition === true) {
     //do some work
     FunctionToCall();
  }
  //do some more work
}

function FunctionToCall() {...}

If ever I call the FunctionToCall(), I don't want to continue with do some more work. Do I need to put a return true or return false statement after the FunctionToCall(); statement? It seems to work with both.

Thanks.

Upvotes: 0

Views: 101

Answers (4)

Amberlamps
Amberlamps

Reputation: 40448

If you are always using MyFunction() in a void-context, use return;

If FunctionToCall() might also be invoked in a different context, I prefer putting return true/false in the next line.

Upvotes: 0

nhahtdh
nhahtdh

Reputation: 56809

You can just do a return;, since you are ignoring the return value of the function.

Upvotes: 3

Parv Sharma
Parv Sharma

Reputation: 12705

yes you will have to put a return statement after or just before a call to next function like this

return FunctionToCall();

or

FunctionToCall();
return;

Upvotes: 1

James Allardice
James Allardice

Reputation: 165961

As you said, you would need to put a return after the call to FunctionToCall. By the sound of it, it doesn't matter what you return (this will return undefined):

if (SomeCondition === true) {
    //do some work
    FunctionToCall();
    return;
}

If you did care about the result of FunctionToCall, you could return the value returned from that:

return FunctionToCall();

Alternatively, you could use an else, and not bother with a return statement (this will return undefined too):

if (SomeCondition === true) {
    //do some work
    FunctionToCall();
}
else {
    //do some more work
}

Upvotes: 4

Related Questions