DevStud DevStud - 7 months ago 12
Javascript Question

Can i use shortand if else statement in my code

I have one question about shortand if else statement. I just want to learn how can i shortand my js if else statement. Anyone can help me within example using my code ?

I am checking the code if clicked button rel="Like" or other text then do something withing if else statement.

if (REL === 'Like') {
if (!$('#pli' + dataid).length) {
$('#ttl' + dataid).prepend('<div class="pli" id="pli' + dataid + '"></div>');
}
} else if (REL === 'Love') {
if (!$('#plo' + dataid).length) {
$('#ttl' + dataid).prepend('<div class="plo" id="plo' + dataid + '"></div>');
}
}else if (REL === 'Unbelievable') {
if (!$('#phi' + dataid).length) {
$('#ttl' + dataid).prepend('<div class="phi" id="phi' + dataid + '"></div>');
}
}else if (REL === 'Spectacular') {
if (!$('#pha' + dataid).length) {
$('#ttl' + dataid).prepend('<div class="pha" id="pha' + dataid + '"></div>');
}
}else if (REL === 'Emotional') {
if (!$('#pwo' + dataid).length) {
$('#ttl' + dataid).prepend('<div class="pwo" id="pwo' + dataid + '"></div>');
}
}

if (REL === 'NotLike') {
setTimeout(function() {
if ($("#sum" + dataid).text() == 0) {
$("#pli" + dataid).remove();
}
}, 200);
}else if (REL === 'NotLove') {
setTimeout(function() {
if ($("#sum" + dataid).text() == 0) {
$("#plo" + dataid).remove();
}
}, 200);
}else if (REL === 'NotUnbelievable') {
setTimeout(function() {
if ($("#sum" + dataid).text() == 0) {
$("#phi" + dataid).remove();
}
}, 200);
}else if (REL === 'NotSpectacular') {
setTimeout(function() {
if ($("#sum" + dataid).text() == 0) {
$("#pha" + dataid).remove();
}
}, 200);
}else if (REL === 'NotEmotional') {
setTimeout(function() {
if ($("#sum" + dataid).text() == 0) {
$("#pwo" + dataid).remove();
}
}, 200);
}

Answer

Switch will definitely help make the code cleaner and more readable. Also I would suggest making a map, a lot of the code is duplicated.

below is an example

if ( [ 'Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional' ].indexOf( REL ) !== -1 ) {
    var map = { 'Like': 'pli', 'Love': 'plo', 'Unbelievable': 'phi' };
    if ( !$( '#' + map[ REL ] + dataid ).length ) {
        $( '#ttl' + dataid).prepend( '<div class="' + map[ REL ] + '" id="' + map[ REL ] + dataid + '"></div>' );
    }
}

if ( [ 'NotLike', 'NotLove', 'NotUnbelievable', 'NotSpectacular', 'NotEmotional' ].indexOf( REL ) !== -1 ) {
    var map = { 'NotLike': 'pli', 'NotLove': 'plo', 'NotUnbelievable': 'phi' };
    setTimeout( function () {
        if ( $('#sum' + dataid).text() == 0 ) {
            $( '#' + map[ REL ] + dataid ).remove();
        }
    }, 200 );
}