0

I'm using the script below to detect city and state from geo.js, but sometimes city comes back as 'undefined' because city is not returned in the array response. How can I detect if json.city is undefined and show something else in "citybody" if city is not detected?

<script async src="https://get.geojs.io/v1/ip/geo.js"></script>
<script type="application/javascript">

        function geoip(json){
        var userip      = json.ip;
    var city      = json.city;
    var region      = json.region;
    
    console.log (json.city);
    console.log (json.region);
    console.log (json.ip);
    

    document.getElementById("city").innerHTML = json.city ;
    document.getElementById("region").innerHTML = json.region ;
    document.getElementById("citybody").innerHTML = json.city ;
    document.getElementById("regionbody").innerHTML = json.region ;
    document.getElementById("region3").innerHTML = json.region ;
 }   
</script>

I've tried using json.city != 'undefined' but does not work.

  • `json.city || 'Unkown city'` – technophyle Jan 12 '23 at 20:37
  • `json.city != null` will check to see that the property is neither null nor undefined. You could also (as mentioned in the other comment) just test `json.city` as if it were a boolean value, which will also tell you if it's non-null but it's an empty string. – Pointy Jan 12 '23 at 20:39
  • city isn't even being returned though so i can't check to see if the values are valid. Example response returned: geoip({"country":"United States","country_code":"US","country_code3":"USA","continent_code":"NA","region":"Rhode Island","accuracy":100,"area_code":"0","timezone":"America\/New_York"}) – I suck at coding Jan 12 '23 at 20:49
  • Note that `null` and `undefined` should **not** be in quotes; that is, not `"undefined"`, because that's a non-empty string and not the value `undefined`. – Pointy Jan 12 '23 at 21:15

0 Answers0