DevStud DevStud - 7 months ago 27
Javascript Question

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

I have created the following if else statement but there are so many if else statement. I want to learn how can i make it shorthand?

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');
}

Answer

Just take the variable with a check.

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

For a flip-flop based on strings starting with 'Not', you may 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);
}