Thank goodness for the video

Tell us what’s happening:
I passed this without any understanding. Had to get a hint and just followed that lead. The video explained and I would like to check.
This is an alternative to if statements.
I guess you use it when searching for a set range of possibilities and you want an output from that specified list.
Any general explanation of how it might be used would be appreciated. Never heard of switch before.

Your code so far

function caseInSwitch(val) {
var answer = "";
// Only change code below this line
case 1:
return "alpha";
case 2:
return "beta";
case 3:
return "gamma";
case 4:
return "delta";


// Only change code above this line
return answer;


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Selecting from Many Options with Switch Statements

Link to the challenge:

This is the challenge it is introduced

Anyway, it can be used when you have multiple possible values for a variable, and you need to do specific things for the values

for example I used a switch statement when fixing some authors spelled wrong in a list of quotes with something like the following

I think the use of mutiple cases executing the same code is one of the next challenges, but just as an anticipation, once a case is satisifed the code execute until next break (or a return)

switch (author) {
   case "William Shakespere":
   case "W. Shakespear":
      author = "William Shakespeare";
   case "Einstein":
      author = "Albert Einstein";

or recently this: (it’s checking if an user can start a quest, for those listed it depends on user level, so I check the user lever)

      switch (quest) {
        case 'atom1':
        case 'atom2':
        case 'atom3':
          return !userLevel < 15;
        case 'vice1':
        case 'vice2':
        case 'vice3':
          return !userLevel < 30;
        case 'goldenknight1':
        case 'goldenknight2':
        case 'goldenknight3':
          return !userLevel < 40;
        case 'moonstone1':
        case 'moonstone2':
        case 'moonstone3':
          return !userLevel < 60;
          return true;

the above is instead of writing

if (quest === "atom1" || quest === "atom2" || quest === "atom3") {
  return !userLevel < 15;
} else if ( ...

it’s more compact, easier to debug, and better suited to this easy comparison of values

1 Like

Okay, thanks that is interesting.