admin管理员组

文章数量:1287961

I have a plicated 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.

I have a plicated 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.

Share Improve this question edited Sep 29, 2017 at 12:32 jcalz 330k29 gold badges439 silver badges442 bronze badges asked Sep 28, 2017 at 16:55 JanierJanier 4,45211 gold badges49 silver badges100 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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; }

本文标签: JavaScriptTypescript returnbreak from a void methodStack Overflow