1

I have some simple code. The problem im facing is that how you can see the code is not very clean because in every line where a string gets added to var text i would like to check if the data i want to add really is defined. Now i would like to know how i can write this more cleaner? Thanks

var text = '<br><address><strong>' + data.vorname + ' ' + data.name + '</strong><br>';
if(data.strasse != null && data.strasse != ''){
    text += data.strasse + '<br>' + data.plz + ', ' + data.wohnort ;  
}if(data.telefon != null && data.telefon != ''){
    text += '<br><strong>Tel: ' + data.telefon + '</strong>';
}
    text += '<br><strong>Handy: ' + data.handy + '</strong><br>';
    text += '<a href="mailto:#">' + data.mail;
    text += '</a></address><address><strong>GEB: </strong>';
    text += Data.datum(data.geburtsdatum) + '<br>';
    text += data.gewicht + '<strong> GK';
    ........
John Smith
  • 6,105
  • 16
  • 58
  • 109

1 Answers1

1

You could rewrite your lines like this:

text += (data.handy)? '<br><strong>Handy: ' + data.handy + '</strong><br>' : '';

This is shorthand for this:

   if (data.handy) {

        text += '<br><strong>Handy: ' + data.handy + '</strong><br>';

   } else {

        text += '';
   }

That way, if data.handy isn't defined or is null then nothing gets added to text.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • But it would the additional text if data.handy were an empty string. – Barbara Laird Feb 10 '14 at 23:29
  • The conditions aren't clear, may be it's (data.handy) in case the data needs to be just defined, may be it should be (data.handy && data.handy.length) That'd be up to the OP; I'm just answering the question based on how the code is currently written, which also has the side effect you're describing. – frenchie Feb 10 '14 at 23:31
  • Not trying to be difficult, but the OP's code checks for empty strings: if(data.strasse != null && data.strasse != ''){ – Barbara Laird Feb 10 '14 at 23:34
  • Well the OP asked for his code to be cleaner and the syntax I'm proposing achieves that. I'm not rewriting every line, just providing a format with cleaner syntax. – frenchie Feb 11 '14 at 16:03