1

I have a switch case, and I want to direct 3 different possible cases to one outcome using the double pipe.

http://jsfiddle.net/qCA3G/

var type = "JPEG"

switch(type){
    case "PNG" || "JPG" || "JPEG":
    alert("works");
    break;
    default:
    alert("not working");
    break;
}

The obvious thing to do would be making a separate case for each of the file types, but there must be a more efficient way, that resembles my attempt.

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
  • 5
    Read about "switch fallthrough". – elclanrs Sep 25 '13 at 02:23
  • Does this answer your question? [Switch statement multiple cases in JavaScript](https://stackoverflow.com/questions/13207927/switch-statement-multiple-cases-in-javascript) – Orchis Aug 18 '20 at 15:01

4 Answers4

7

This is why switch has fall-through:

switch(type){
    case "PNG":
    case "JPG": 
    case "JPEG": 
       alert("works");
       break;
    default:
       alert("not working");
       break;
}

But fallthrough is a fickle beast! Beware the dreaded forgotten break statement

switch(type){
    case "PNG":
    case "JPG": 
    case "JPEG": 
       alert("works");
    default: // forgot break BOTH ALERTS RUN!
       alert("not working");
       break;
}
Doug T.
  • 64,223
  • 27
  • 138
  • 202
2

That's not the way switch case works. You need to instead create fall-through case'(skipping the break statement).

var type = "JPEG"

switch(type){
    case "PNG":  
    case "JPG":  
    case "JPEG":  
       alert("works");
    break; //break here if you dont want to fall through again
    default:
       alert("not working");
    break;
}
PSL
  • 123,204
  • 21
  • 253
  • 243
1

Yeah, there is:

        var type = "JPEG"

        switch (type) {
        case "PNG":
        case "JPG":
        case "JPEG":
            alert("works");
            break;
        default:
            alert("not working");
            break;
        }
Thomas
  • 1,401
  • 8
  • 12
1

Try

var type = "JPEG"

switch(type){
    case "PNG":
    case "JPG":
    case "JPEG":
      alert("works");
    break;
    default:
      alert("not working");
    break;
}
Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70