Search code examples
javascriptswitch-statementone-liner

Compact one-liner for each case statement in a switch statement - JavaScript


I couldn't find any documentation or questions about whether it's possible to write the case statements in a switch statement on one line nor what the best practice and way to write them on one line in JavaScript is.

The most related questions were: CodeGrepper Question and Switch statement for multiple cases in JavaScript

I currently have a function with a switch statement that returns a product's name:

function returnProduct(product) {
    switch (product) {
        case 'aa': case 'AApple':
            return 'AApple';
        case 'bb': case 'BananaBall':
            return 'BananaBall';
        case 'ee': case 'ElephantElf':
            return 'ElephantElf';
        default:
            return 'Sorry we don\'t have that yet';
    }
}

console.log(returnProduct('aa'));
console.log(returnProduct('error'));
console.log(returnProduct('ee'));
console.log(returnProduct('BananaBall'));


Solution

    • Solution 1

      Thanks to @Ryan Wheale, @Bergi and @T.J. Crowder who helped me realize that since Javascript doesn't require line breaks it could all be written on one single line separated by; and I don't need to put any {} around the return statements. While the following code snippet does answer my question, it's also important to mention that a one liner like this is not at all readable and should be avoided.

    function returnProduct(product) { switch (product) { case 'aa': case 'AApple': return 'AApple'; case 'bb': case 'BananaBall': return 'BananaBall'; case 'ee': case 'ElephantElf': return 'ElephantElf'; default: return 'Sorry we don\'t have that yet'; } } console.log(returnProduct('aa')); console.log(returnProduct('error')); console.log(returnProduct('ee')); console.log(returnProduct('BananaBall'));


    • Solution 2: This solution is a bit more readable and still achieves my original goal of creating a compact switch statement.

    function returnProduct(product) {
            switch (product) {
                case 'aa': case 'AApple': return 'AApple';
                case 'bb': case 'BananaBall': return 'BananaBall';
                case 'ee': case 'ElephantElf': return 'ElephantElf';
                default: return 'Sorry we don\'t have that yet';
            }
        }
    
        console.log(returnProduct('aa'));
        console.log(returnProduct('error'));
        console.log(returnProduct('ee'));
        console.log(returnProduct('BananaBall'));

    This was my first proposed solution which solves my problem but I hadn't tested it enough and had some errors which the community helped me fix.

    I hope that others asking the same question will be able to find this as a useful answer to the same question I had.