Last Updated: February 25, 2016
·
506
· kyen

Switch off

Instead of a bulky switch/case, like this:

var out = "";
switch(lang)
{
    case "JavaScript":
        out = "JS";
        break;
    case "Ruby":
        out = "RB";
        break;
    case "C#":
        out = "CS";
        break;
    default:
        out = "CPP";
        break;
}

Just do a complex ternary, like this:

var out = lang == "JavaScript" ? "JS"
            :  lang == "Ruby" ? "RB"
            :  lang == "C#" ? "CS"
            :  "CPP";

It's much cleaner and smaller, and even takes less time to write!

2 Responses
Add your response

I prefer doing that way

var langs = {
    'javascript': 'JS',
    'ruby': 'RB',
    'c#': 'CS',
    'cpp': 'CPP',
};
var out = langs[lang.toLowerCase()] || 'CPP';
over 1 year ago ·

All just a matter of stylistic preference :D

over 1 year ago ·