replacing if else chains with switch

Solutions on MaxInterview for replacing if else chains with switch by the best coders in the world

showing results for - "replacing if else chains with switch"
Federico
13 Feb 2018
1function chainToSwitch(val) {
2  var answer = "";
3
4  if (val === "bob") {
5    answer = "Marley";
6  } else if (val === 42) {
7    answer = "The Answer";
8  } else if (val === 1) {
9    answer = "There is no #1";
10  }
11  
12  // and now with switch
13  switch(val){
14    case "bob":
15      answer = "Marley";
16      break;
17    case 42:
18      answer = "The Answer";
19      break;
20    case 1:
21      answer = "There is no #1";
22      break;
23  }
24
25  return answer;
26}
Anna
02 Sep 2020
1function chainToSwitch(val) {
2
3  var answer = "";
4  
5  switch(val){
6    case "bob":
7    answer = "Marley";
8    break;
9    case 42:
10    answer = "The Answer";
11    break;
12    case 1:
13    answer = "There is no #1";
14    break;
15    case 99:
16    answer = "Missed me by this much!";
17    break;
18    case "John":
19    answer = "";
20    break;
21    case 156:
22    answer = "";
23    break;
24    default:
25    answer = "Ate Nine";
26  }
27
28  return answer;
29}
30
31chainToSwitch(7);