NL1 NL1 - 1 month ago 9
Javascript Question

How to delete return value if variable is blank in javascript

I have written one function :

function abcd(gg,hh,ii,jj){
return "Hi,\n\nBelow is alert."\n\n"+gg+"\n"+hh+"\n"+ii+"\n"+jj+";
}


where 4 variables gg,hh,ii,jj has written globally and calling dynamically. where 'gg' containg 'Approval is done', 'hh' containg 'Approval is done', 'ii' containg 'Approval is done', 'jj' containg 'Approval is done'. My concern is sometime i have value for gg , hh, ii or jj and sometime not and i am getting output as below if i have value for all variable by mentioned above Function code:

Hi,

Below is alert.

Approval is done.
Approval is done.
Approval is done.
Approval is done.


So If 'ii' is blank then i need as below, but my code is returning line space if 'ii' is blank:

Hi,

Below is alert.

Approval is done.
Approval is done.
Approval is done.

Answer

Probably the cleanest, with how you have it, would be something like this:

function abcd(gg,hh,ii,jj){
    return "Hi,\n\nBelow is alert.\n\n" 
        + (gg ? gg + "\n" : '')
        + (hh ? hh + "\n" : '')
        + (ii ? ii + "\n" : '')
        + jj;
}

The ternary operator (?:) is in the format condition ? if_true : if_false. You can check for a "falsy" value on the string (null and '' both count as false), so it'll only output stuff if it's not falsey.

Comments