Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable is empty in JavaScript?

Tags:

javascript

var characterName = document.getElementById("pilotName").value;
var characterID = 0;
var charSecStatus = 0;
var corpName = " ";
var allianceName = " ";


//callback
makeRequest('https://api.eveonline.com/eve/CharacterID.xml.aspx?names=' + characterName, function() {
  if (xmlhttp.status == OK_RESPONSE) {

    //read character info
    characterID = xmlhttp.responseXML.getElementsByTagName("row")[0].getAttribute("characterID");

    makeRequest('https://api.eveonline.com/eve/CharacterInfo.xml.aspx?characterID=' + characterID, function() {

      if (xmlhttp.status == OK_RESPONSE) {

        //read character info 
        characterID = xmlhttp.responseXML.getElementsByTagName("characterID")[0].innerHTML;
        charSecStatus = xmlhttp.responseXML.getElementsByTagName("securityStatus")[0].innerHTML;
        corpName = xmlhttp.responseXML.getElementsByTagName("corporation")[0].innerHTML;
        allianceName = (xmlhttp.responseXML.getElementsByTagName("alliance")[0] || {
          innerHTML: ""
        }).innerHTML;
      }
    });
  }
});

(partial code pictured, no bracketspam pls) I'm trying to check if the "alliance" variable is empty because certain '"corp" are not in "alliances" and it would be critical error on website if it tried to display an empty variable, so is there a way to check if allianceName is empty after retrieving it from the XML tree and setting it to like "No Alliance" if it IS empty? Thanks

like image 351
timoxazero Avatar asked Jun 16 '26 04:06

timoxazero


1 Answers

You are declaring true variables here

var corpName = " ";
var allianceName = " "

In JavaScript, the value of a string with whitespace characters is actually truthy. While the above values do look empty, the reality is they're not. Try it out yourself.

Boolean(" ");
=> true

To set these variables empty, you need to declare them without whitespace characters

var corpName = "";
var allianceName = "";

After you have this, there are two ways to check if the variable is empty

if (!corpName || !corpName.length)

Assuming, you did accidentally include the whitespace character, there are several ways to fix this. We can modify these strings in these cases.

Boolean(" ".trim());
=> false

In the above example, the trim() function is used to remove whitespace characters from a string.

You could also search the string for non-whitespace characters

/\S/.test(" ")
=> false

The \S modifier finds all non whitespace characters.

Alternatively, you could also use the replace function

Boolean(" ".replace(/\s/g, ''));

The global flag g finds all references to the previous regular expression.

like image 105
Richard Hamilton Avatar answered Jun 17 '26 19:06

Richard Hamilton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!