Question about Switch Statements

I had a quick question to clarify and help me understand switch statements . I was going through the beginners Javascript module and ran across this code:

 function caseInSwitch(val) {
  var answer = "";

       case 1:
       answer = "alpha";

       case 2:
   answer = "beta";

      case 3: 
  answer = "gamma"

     case 4: 
 answer = "delta"

return answer;

The way I understand it, is that we create a function that asks for val. In that function we then create a variable named answer and then use a switch, to assign answer a string, and at the end we return our variable string, which was obtained through a case.

So for the switch statement, it takes the input here from val, runs through the cases, and once it finds a match it stops with the break; statement, and then skips the rest and finishes with the return answer

So within each case, it’s changing the variable answer 's value to whatever the new string is?

Sorry if this is simple! I’m very new and it’s my first post.

Hey @K_Man!

Everytime you call the function and pass through an argument of 1,2,3, or 4 then the program is going to find that case that matches the argument and return the answer from that case.

Switch statements are just another alternative to if else statements.

Hope that helps!

Happy coding!

1 Like

Thanks! So for the case, it can be a string too right? So instead of case 1: , if we want the user to enter strings we can make it case “one”:

Also, would the default option act similarly to an “else” at the end of an if else chain?

If you tried to call the function and pass through “one” instead of the number 1 then technically that string would not match any of your cases.

The next lesson actually covers default cases and those are similar to the “else” in if else statements.

1 Like