Checking if-statement condition for! = "Undefined" fails

I am trying to generate some HTML content for Google Maps infowindow. I have 7 values ​​that should be displayed if they are not zero, undefined or "" (empty string).

But apparently my if(e.Property != null || e.Property != "undefined" || e.Property == "") does not work if Property is undefined . Basically, e.Email is undefined. So instead of skipping this part, my code still inserts the html + "<br /> . And when I alert() , e.Email returns undefined , which it should catch and skip if it is.

I tried writing if(typeof e.Property != null || typeof e.Property != "undefined" || typeof e.Property == "") , but that didn't matter.

 // 'e ' is JSON object var generateHTML = { init: function(e) { if (e != null || e != "undefined"){ generateHTML.check(e); } }, check: function (e) { if(e.Title != null || e.Title != "undefined" || e.Title == ""){ html = html + "<b>"+e.Title+"</b>"; } if(e.Address != null || e.Address != "undefined" || e.Address == ""){ html = html +"<br />"+ e.Address; } if(e.Zipcode != null || e.Zipcode != "undefined" || e.Zipcode == ""){ html = html +"<br />"+ e.Zipcode+", "; } if(e.City != null || e.City != "undefined" || e.City == ""){ html = html + e.City; } if(e.Phone != null || e.Phone != "undefined" || e.Phone == ""){ html = html +"<br />"+ e.Phone; } if(e.Email != null || e.Email != "undefined" || e.Email == ""){ html = html +"<br />"+ e.Email; } if(e.WebAddress != null || e.WebAddress != "undefined" || e.WebAddress == ""){ html = html +"<br />"+ e.WebAddress; } return html; } }; 
+7
source share
6 answers

If you want to use a shorter version you can use:

 if (e.Title) { // add to HTML } if (e.Address) { // add to HTML } 

You might want to build your HTML as an array and then join at the end to avoid creating multiple lines, for example.

 var html = []; html.push("FirstName"); html.push("<br />"); html.push("LastName"); html.push("<br />"); html.push("Number"); var output = html.join(""); // "FirstName<br />LastName<br />Number" 
+2
source

You want to check out! == undefined

eg.

 if(myvar !== undefined) { //DO SOMETHING } 
+5
source
 if(e) //this would be shorter if(e != undefined) // if(typeof(e) != 'undefined') 
+3
source

undefined is the name of the variable, not a string.

You do not need quotes around it.

+1
source

You check it as if its value was the string "undefined"

delete "

+1
source

it is better to check something using variable type e.length reasons are not explicit in javascript

0
source

All Articles