Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute somethnig `finally` in Javascript swich-case statement?

In javascript switch statements, I would like to execute some function if any one of the case is satisified:

switch (myVar){
  case 0:
    do_something_0();
    break;
  case 1:
    do_something_1();
    break;
  // I want to execute myFunc() if myVar === 1 or myVar === 2
}

I came up with the idea of having auxiliary variable haveMatched, like this.

var haveMatched=false;
switch (myVar){
  case 0:
    do_something_0();
    haveMatched=true;
    break;
  case 1:
    do_something_1();
    haveMatched=true;
    break;
}
if (haveMatched){
  do_finally();
}

I think there might be better way of achieving this (for example, I would've tried the similar way if I hadn't known about the default: keyword). Am I doing it right, or am I missing something?

like image 368
Yosh Avatar asked May 28 '14 03:05

Yosh


1 Answers

If you rewrite your code to include a default case you don't have to include haveMatched = true in every case.

var haveMatched=true;
switch (myVar){
  case 0:
    do_something_0();
    break;
  case 1:
    do_something_1();
    break;
  default:
    haveMatched = false;
}
if (haveMatched){
  do_finally();
}
like image 75
powerc9000 Avatar answered Nov 15 '22 19:11

powerc9000