 # Replacing If Else Chains with Switch

## Solutions

Solution 1 (Click to Show/Hide)

We need to change the chained `if/else if` statements into a `switch` statement.

Now, we need to comment (`//` - select all lines and `ctrl+/`) all chained `if/else if` statements:

``````//   if (val === "bob") {
//   } else if (val === 42) {
//   } else if (val === 1) {
//     answer = "There is no #1";
//   } else if (val === 99) {
//     answer = "Missed me by this much!";
//   } else if (val === 7) {
//   }
``````

Next, we need to create simple `switch` statement:

``````switch (val) {
}
``````

and add in this `switch` statement `case` - for all `if/else if` statement (just copy it from our commented code above):

``````switch (val) {
case "bob":
break;
case 42:
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case 7:
break;
}
``````

Dont forget to use `break` in each `case`!
Now, we can delete commented code with `if/else if` statement above.

Here’s a full solution:

``````function chainToSwitch(val) {
// Only change code below this line
switch (val) {
case "bob":
break;
case 42:
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case 7:
break;
}
// Only change code above this line
}
// Change this value to test
chainToSwitch(7);
``````
6 Likes

Try this.

function chainToSwitch(val) {
// Only change code below this line
switch (val) {
case “bob”:
break;
case 42:
break;
case 1:
answer = “There is no #1”;
break;
case 99:
answer = “Missed me by this much!”;
break;
case “John”:
break;
case 156:
break;
default:
}

6 Likes

Make sure you make “case bob” a string, I spent minutes trying to figure out what was wrong with my code.

5 Likes

## One tip:

At first I commented out the original statement given. One thing I notice is that there should really by no Else / If / Else on the editor. Even though those expressions are commented out.

``````  **if** (val === "bob") {
} **else if** (val === 42) {
} **else if** (val === 1) {
answer = "There is no #1";
} **else if** (val === 99) {
answer = "Missed me by this much!";
} **else if** (val === 7) {
}
``````
1 Like

Try this. It applied for me.

function chainToSwitch(val) {
// Only change code below this line

switch(val){
case “bob”:
break;
case 42:
break;
case 1:
answer = “There is no #1”;
break;
case 99:
answer = “Missed me by this much!”;
break;
case “John”:
break;
case 156:
break;
case 7: