Switch Statement for Multiple Cases in JavaScript

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');
}

Test for multiple cases in a switch, like an OR (||)

You can use fall-through:

switch (pageid)
{
case "listing-page":
case "home-page":
alert("hello");
break;
case "details-page":
alert("goodbye");
break;
}

Why is my switch statement running multiple cases?

It's because you don't have a break statement. Without it, the code will "fall through".

var x = 10;switch (x) {  case 10:    console.log('With break');    break;      case 20:    console.log('I never run');    break;}
console.log('-------');
switch (x) { case 10: console.log('Without'); case 20: console.log('a break'); case 30: console.log('it just'); case 40: console.log('keeps going');}

JavaScript, Typescript switch statement: way to run same code for two cases?

Just put them right after each other without a break

switch (myVar) {
case 68:
case 40:
// Do stuff
break;

case 30:
// Do stuff
break;
}

Javascript Switch Statement multiple cases return the values

You could take an object with the wanted values and get an array of strings.

var values = { Beef: "Cows", Pork: "Pigs", Sheep: "Sheep", Goat: "Goats", Lamb: "Lambs", Rabbit: "Rabbit", OtherMeat: "Other", Chicken: "Chicken", Turkey: "Turkey", Duck: "Duck", Goose: "Geese", Pheasant: "Pheasants", Quail: "Quail", OtherPoultry: "Other Poultry" };
result = Object
.keys(popup.properties)
.filter(k => popup.properties[k] === 'Yes')
.map(k => values[k]);

Javascript Switch: can you use the same case multiple times?

No, it doesn't work. It only seems to work because you are missing a break after the first case. Without that break, if the second case was called anything, it would be executed.

For instance, if you called the second case case 'foo': it would still set height/width properties. The height and width are applied because of the missing break in the previous case statement.

Credit @machinegost and @jorg for the following additional sources, respectively:

  • https://help.semmle.com/wiki/display/JS/Duplicate+switch+case
  • ECMA 2015 Spec: Switch Statement Static Semantics (Early Errors)

Switch always hits Default Case JS

Instead of using switch you could build a little dictionary object, and then reference the values using the key. It's a little less unwieldy.

const obj = {
DAR: 'Delivered and Recieved',
DCR: 'Delivery Completion Rate'
};

function setTitle(data) {
console.log(data);
}

function handleOption(option) {
setTitle(obj[option]);
}

handleOption('DAR');
handleOption('DCR');


Related Topics



Leave a reply



Submit