48

This is just a simple example of what I'm trying to do:

switch (window.location.href.contains('')) {
    case "google":
        searchWithGoogle();
        break;
    case "yahoo":
        searchWithYahoo();
        break;
    default:
        console.log("no search engine found");
}

If it's not possible/feasible what would be a better alternative?

Solution:

After reading some of the responses I found the following to be a simple solution.

function winLocation(term) {
    return window.location.href.contains(term);
}
switch (true) {
    case winLocation("google"):
        searchWithGoogle();
        break;
    case winLocation("yahoo"):
        searchWithYahoo();
        break;
    default:
        console.log("no search engine found");
}
RayB
  • 2,096
  • 3
  • 24
  • 42

2 Answers2

35

"Yes", but it won't do what you expect.

The expression used for the switch is evaluated once - in this case contains evaluates to true/false as the result (e.g. switch(true) or switch(false)) , not a string that can be matched in a case.

As such, the above approach won't work. Unless this pattern is much larger/extensible, just use simple if/else-if statements.

var loc = ..
if (loc.contains("google")) {
  ..
} else if (loc.contains("yahoo")) {
  ..
} else {
  ..
}

However, consider if there was a classify function that returned "google" or "yahoo", etc, perhaps using conditionals as above. Then it could be used as so, but is likely overkill in this case.

switch (classify(loc)) {
   case "google": ..
   case "yahoo": ..
   ..
}

While the above discusses such in JavaScript, Ruby and Scala (and likely others) provide mechanisms to handle some more "advanced switch" usage.

user2864740
  • 60,010
  • 15
  • 145
  • 220
19

An alternative implementation might be this. Not much in it but reads better than switch(true)...

const href = window.location.href;
const findTerm = (term) => {
  if (href.includes(term)){
    return href;
  }
};

switch (href) {
  case findTerm('google'):
      searchWithGoogle();
      break;
  case findTerm('yahoo'):
      searchWithYahoo();
      break;
  default:
      console.log('No search engine found');
};
TimT
  • 1,576
  • 16
  • 14