Replacing If Else Chains with Switch
If you have many options to choose from, a switch
statement can be easier to write than many chained if
/else if
statements. The following:
if (val === 1) {
answer = "a";
} else if (val === 2) {
answer = "b";
} else {
answer = "c";
}
can be replaced with:
switch (val) {
case 1:
answer = "a";
break;
case 2:
answer = "b";
break;
default:
answer = "c";
}
Change the chained if
/else if
statements into a switch
statement.
Tests
- Waiting: 1. You should not use any
else
statements anywhere in the editor - Waiting: 2. You should not use any
if
statements anywhere in the editor - Waiting: 3. You should have at least four
break
statements - Waiting: 4.
chainToSwitch("bob")
should return the stringMarley
- Waiting: 5.
chainToSwitch(42)
should return the stringThe Answer
- Waiting: 6.
chainToSwitch(1)
should return the stringThere is no #1
- Waiting: 7.
chainToSwitch(99)
should return the stringMissed me by this much!
- Waiting: 8.
chainToSwitch(7)
should return the stringAte Nine
- Waiting: 9.
chainToSwitch("John")
should return""
(empty string) - Waiting: 10.
chainToSwitch(156)
should return""
(empty string)
/** * Your test output will go here */