HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

User agent classification using switch (true)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
switchuseragenttrueusingclassification

Problem

I've seen usage of switch(true) multiple times and have used it myself today instead of multiple elseifs. 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 if`s. Do you think it's a good approach?

Solution

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.

Code Snippets

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

Context

StackExchange Code Review Q#37424, answer score: 10

Revisions (0)

No revisions yet.