Javascript Tips – A better way to write switch
Switch statement in JavaScript is easy and widely used, but there is a better way to write switch without using switch.
function isSupported(name){
switch(name){
case "Chrome":
return "Fully Supported";
case "Edge":
return "Fully Supported";
case "FireFox":
return "Limited Support";
case "IE":
return "Not supported";
default:
return "Unknown"
}
}
console.log(isSupported("FireFox"))
console.log(isSupported("Opera"))
Above code may seem simple enough, but we can make it better.
function isSupported(name){
const browsers = {
Chrome: "Fully Supported",
Edge: "Fully Supported",
Firefox: "Limited Support",
IE: "Not supported"
}
return browsers[name] ? browsers[name] : "Unknown"
}
console.log(isSupported("FireFox"))
console.log(isSupported("Opera"))
By simply using an object map, we successfully reduced lines of code, it is more readable and more importantly, this is much easy to expand later on by just adding more items to the list.