Replacing Switch statement with objects

June 26, 2020

Switch statement

The switch statement evaluates an expression, and matches the evaluated value to a available case, and executes statements associated with that case

function getGender(genderCode){
    let gender = '';
    switch ( genderCode + 1 ) {
        case 1:
            gender = 'TRANSGENDER';
            break;
        case 2:
            gender = 'FEMALE'
            break;
        case 3:
            gender = 'MALE';
            break;
        default :
            gender = 'AILEN';
    }
    return gender;
}
getGender(0); //TRANSGENDER
getGender(1); //FEMALE

Replacing Switch statement

An object is a key-value pair , we can use key as the label and value as the operations .The same above code with switch statement can be replaced with the objects

var genderObj = {
    1 : 'TRANSGENDER',
    2 : 'FEMALE',
    3 : 'MALE'
};
function getGender(genderCode) {
    return genderObj[genderCode] || 'AILEN';
}

Replacing multiple case with same action

Conside we have a switch statement like

function getFoodType(food){
    switch () {
        case '🥕':
        case '🍅':
        case '🥦':
            return 'VEG';
        case '🥩':
        case '🍗':
        case '🍖':
            return 'NON-VEG'
        default:
           return 'VEG';
      }
}

To replace the above switch statement , you can do like

function getFoodType(food){
    let obj = {
        `🥕` : 'VEG',
        `🍅` : 'VEG',
        '🥦' : 'VEG',
        '🥩' : 'NON-VEG',
        '🍗' : 'NON-VEG',
        '🍖' : 'NON-VEG'
    }
    return obj[food] || 'VEG';
}