razoes
razoes

Reputation: 183

How to use multiple cases in a switch statement

I found this answer in a question similar to mine, but I still have a doubt.

Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found, so you could write it like:

switch (varName) {    
    case "afshin":
    case "saeed":
    case "larry":
        alert('Hey');
        break;

    default: 
        alert('Default case');
}

This means "if varName is afshin && saeed && larry", or it means "if varName is afshin || saeed || larry"?

Thanks in advance!

Upvotes: 0

Views: 91

Answers (1)

spectacularbob
spectacularbob

Reputation: 3228

As the previous answer said

A matched case will run until a break (or the end of the switch statement) is found

To better understand how this works, consider this example:

switch (varName) {    
    case "afshin":
         alert("afshin");

    case "saeed":
         alert("saeed");

    case "larry":
        alert('larry');
        break;

    default: 
        alert('Default case');
}

Since only the "larry" case has the break,

if varName == "afshin", you will get 3 alerts ("afshin","saeed","larry")

if varName == "saeed", you will get 2 alerts ("saeed","larry")

if varName == "larry", you will get 1 alert ("larry")

This is why it is very important to break all of your cases unless you absolutely mean for the case statement to drop through to the next one.

Long story short, writing:

 case "afshin":
 case "saeed":
 case "larry":
      alert("hi");
      break;

is the equivalent of

if(varName == "afshin" || varName == "saeed" || varName == "larry"){
   alert("hi");
}

Upvotes: 2

Related Questions