JavaScript/Typescript return/break from a void method

Viewed 7361

I have a complicated method with if else if else constructs in typescript. Its a void method. How do i break from the method on some particular if condition so that other conditions need not to be executed. This helps me in avoiding the else condition ;I can keep on writing if

In Java this can be achieved using return; inside the void method.

3 Answers

This is the the same in Javascript and Typescript as in Java : you just use a simple return;.

if (true) {
  return;
}

console.log('Never printed')

It is also the same in several other languages I can think of, like C, C++, C#, and many others with some slight variations on the syntax.

You can use an empty return to exit the function execution:

function test() {
  if(true) {
    return;
  } else if (true) {
    console.log('It will not be printed, because "return" is in first "if" statement');
  }
}

test();

May be your value is returning an undefined type. In typescript I check value vs null, but only in some types it works, for other types like Date I have to check with the undefined possibility too, like this:

if (this.creationDate === null || this.creationDate === undefined) { return; }
Related