6
\$\begingroup\$

I've seen usage of switch(true) multiple times and have used it myself today instead of multiple elseif`s. Here is the case I used it for:

var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') != -1;
var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') != -1;
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') != -1;
var browser = null;
switch (true) {
    case isChrome:
        {
            browser = "chrome";
            break;
        }
    case isSafari:
        {
            browser = "safari";
            break;
        }
    case isFirefox:
        {
            browser = "firefox";
            break;
        }
}

My view is that much more explicit than multiple else ifs. Do you think it's a good approach?

\$\endgroup\$
  • \$\begingroup\$ The else-if alternative is shorter and more explicit. \$\endgroup\$ – user29120 Dec 15 '13 at 17:30
10
\$\begingroup\$

Assuming that you bad a bunch of boolean variables already defined, I think a chained ternary conditional expression would be even better, because it's more compact, and also emphasizes that the goal is to assigning something to browser.

var browser = isChrome ? "chrome" :
              isSafari ? "safari" :
              isFirefox ? "firefox" :
              null;

Also consider defining a userAgentContains(…) function to reduce redundancy.

\$\endgroup\$
4
\$\begingroup\$

It kinda looks explicit, but it also looks... weird. Too much going on.

if ... else if (or 200_success's neat ternaries) is shorter and much more conventional, which is a good thing. And with a switch you've got to beware of fall-throughs.

In your example, though, I might simply do:

var browser = (navigator.userAgent.toLowerCase().match(/(chrome|safari|firefox)/) || [null])[0];

Which accomplishes the same thing, really.

Or, if you need to do other stuff, after getting the browser name, then you can use a switch if you want:

var match = navigator.userAgent.toLowerCase().match(/(chrome|safari|firefox)/) || [];
switch( match[0] ) {
  case "chrome":
    ...
    break;
  case "safari":
    ...
    break;
  case "firefox":
    ...
    break;
  default:
    ...
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.