0

I have a function which looks like this:

function myFunc(){
  if (!condition1){
    //some extra code (diff. from condition2 if-statement)
    doSomething();
    return;
  }
  if (!condition2){
    //some extra code (diff. from condition1 if-statement)
    doSomething();
    return;
  }
  //some extra code (diff. from both condition if-statement)
  doSomething();
}

I would like to know if there is a way to simplify this code so the function doSomething() always execute (like in Java with try/catch/finally).

  • If this is javascript, there is try/catch/finally. In addtion, you can combine your conditions into one to accomplish your goal, such as `if(!condition1 || condition2 || ...)`. I really don't understand your question here. – namln-hust May 19 '22 at 03:30
  • May be i didn't understand your question correctly, but if `doSomething` doesn't depend on any conditions, why don't you call it after `myFunc` – ZloiGoroh May 19 '22 at 03:31
  • or you can call once at the end of the function and you have to remove reutrn from if and elseif condition – codewithsg May 19 '22 at 03:32

1 Answers1

0

Using try/catch[optional]/finally solved my problem.

try {
  (function myFunc(){
    if (!condition1){
      //some extra code (diff. from condition2 if-statement)
      return;
    }
    if (!condition2){
      //some extra code (diff. from condition1 if-statement)
      return;
    }
    //some extra code (diff. from both condition if-statement)
  })();
} finally {
  doSomething();
}