Switch statement for multiple cases in JavaScript
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 works in regular JavaScript:
function theTest(val) { var answer = ""; switch( val ) { case 1: case 2: case 3: answer = "Low"; break; case 4: case 5: case 6: answer = "Mid"; break; case 7: case 8: case 9: answer = "High"; break; default: answer = "Massive or Tiny?"; } return answer;}theTest(9);
Here's different approach avoiding the switch
statement altogether:
var cases = { afshin: function() { alert('hey'); }, _default: function() { alert('default'); }};cases.larry = cases.saeed = cases.afshin;cases[ varName ] ? cases[ varName ]() : cases._default();