How can I use shorthand if else stament in my js code

I created the following if else statement, but there are so many if if else. I want to know how can I make it shortened?

if(REL == 'Like'){
   $('#Like' + dataid).attr('rel', 'NotLike');
} else if(REL == 'Love') {
   $('#Love' + dataid).attr('rel', 'NotLove');
} else if(REL == 'Unbelievable'){
   $('#Unbelievable' + dataid).attr('rel', 'NotUnbelievable');
} else if(REL == 'Spectacular'){
   $('#Spectacular' + dataid).attr('rel', 'NotSpectacular');
} else if(REL == 'Emotional'){
   $('#Emotional' + dataid).attr('rel', 'NotEmotional');
}
+4
source share
1 answer

Just take the variable with validation.

if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(REL) !== -1) {
    $('#' + REL + dataid).attr('rel', 'Not' + REL);
}

For a trigger based on lines starting with 'Not', you can use this

var temp = REL,
    not = 'Not';

if (REL.substring(0, 3) === 'Not') {
    temp = REL.substring(3);
    not = '';
}
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
    $('#' + REL + dataid).attr('rel', not + temp);
}

Stateful Offer

var lastState = '';

function change(state) {
    var temp = state,
        not = 'Not';
    if (state.substring(0, 3) === 'Not') {
        temp = state.substring(3);
        not = '';
    }
    if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
        $('#' + temp + dataid).attr('rel', not + temp);
    }
    return not + temp;
}

// usage always both together:
change(lastState);       // to reset the last state
lastState = change(REL); // call change and save the actual state
+14
source

All Articles