freeCodeCamp/guide/english/certifications/javascript-algorithms-and-d.../basic-javascript/replacing-if-else-chains-wi.../index.md

119 lines
2.6 KiB
Markdown
Raw Normal View History

2018-10-19 12:53:51 +00:00
---
title: Replacing If Else Chains with Switch
---
## Replacing If Else Chains with Switch
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Heres the setup:
```javascript
function chainToSwitch(val) {
var answer = "";
// Only change code below this line
switch(val) {
case "bob":
answer = "Marley";
break;
case 42:
answer = "The Answer";
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case 7:
answer = "Ate Nine";
break;
}
2018-10-19 12:53:51 +00:00
// Only change code above this line
return answer;
}
// Change this value to test
chainToSwitch(7);
```
We need to change the chained ```if/else if``` statements into a ```switch``` statement.
Heres a solution:
2018-10-19 12:53:51 +00:00
Now, we need to comment (```//``` - select all lines and ```ctrl+/```) all chained ```if/else if``` statements:
2018-10-19 12:53:51 +00:00
```javascript
// if (val === "bob") {
// answer = "Marley";
// } else if (val === 42) {
// answer = "The Answer";
// } else if (val === 1) {
// answer = "There is no #1";
// } else if (val === 99) {
// answer = "Missed me by this much!";
// } else if (val === 7) {
// answer = "Ate Nine";
// }
```
2018-10-19 12:53:51 +00:00
Next, we need to create simple ```switch``` statement:
2018-10-19 12:53:51 +00:00
```javascript
switch(val) {
2018-10-19 12:53:51 +00:00
}
```
2018-10-19 12:53:51 +00:00
and add in this ```switch``` statement ```case``` - for all ```if/else if``` statement (just copy it from our commented code above):
2018-10-19 12:53:51 +00:00
```javascript
switch(val) {
case "bob":
answer = "Marley";
break;
case 42:
answer = "The Answer";
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case 7:
answer = "Ate Nine";
break;
}
2018-10-19 12:53:51 +00:00
```
Dont forget to use ```break``` in each ```case```!
Now, we can delete commented code with ```if/else if``` statement above.
2018-10-19 12:53:51 +00:00
Heres a full solution:
2018-10-19 12:53:51 +00:00
```javascript
function chainToSwitch(val) {
var answer = "";
// Only change code below this line
switch(val) {
case "bob":
answer = "Marley";
break;
case 42:
answer = "The Answer";
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case 7:
answer = "Ate Nine";
break;
2018-10-19 12:53:51 +00:00
}
// Only change code above this line
return answer;
}
// Change this value to test
chainToSwitch(7);
```