I have a switch case, and I want to direct 3 different possible cases to one oute using the double pipe.
/
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.
I have a switch case, and I want to direct 3 different possible cases to one oute using the double pipe.
http://jsfiddle/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.
Share Improve this question asked Sep 25, 2013 at 2:22 Philip KirkbridePhilip Kirkbride 22.9k39 gold badges131 silver badges237 bronze badges 2- 5 Read about "switch fallthrough". – elclanrs Commented Sep 25, 2013 at 2:23
- Does this answer your question? Switch statement multiple cases in JavaScript – Orchis Commented Aug 18, 2020 at 15:01
4 Answers
Reset to default 7This 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;
}
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;
}
Yeah, there is:
var type = "JPEG"
switch (type) {
case "PNG":
case "JPG":
case "JPEG":
alert("works");
break;
default:
alert("not working");
break;
}
Try
var type = "JPEG"
switch(type){
case "PNG":
case "JPG":
case "JPEG":
alert("works");
break;
default:
alert("not working");
break;
}