Switch (true) As Alternative To Else If
I've seen multiple times usage of switch(true) and have used it today myself instead of multiple else ifs. Here is the case I used it for: var isChrome = navigator.userAgent.toLowe
Solution 1:
It's really just a matter of personal opinion. switch(true)
may be confusing at first, but it really doesn't matter with regards to speed or semantics. I, personally think that if...else
looks better in this case, since there are so few options. If there were 10-15 browsers, I might use a switch
.
If you're looking for pure conciseness, @adeneo's regular expression would work, but that would be even harder to understand, with this code
var ua = navigator.userAgent.toLowerCase(),
browser = ua.match(/(chrome|safari|firefox)/).length ? ua.match(/(chrome|safari|firefox)/)[0] : 'nope';
console.log(browser);
which looks really cool and concise, but seems a bit unintuitive. I'd just say that whatever you want to do is fine, there's no standard for things like this.
Post a Comment for "Switch (true) As Alternative To Else If"