Search code examples
javascriptecmascript-5

Javascript test for null array not working


I'm using a tool that has Javascript ES5. I'm trying to test if an array is null or not via an if condition. The output of the array before the if states its "null" (see test result below); however, when the if condition check is done for "null" it thinks it should continue processing when it shouldn't. I've checked for a null array various ways via the if statement and it still passes the test and aborts because of the null array value when I dump the debug data and specify [_OFNBRindex] on the array (currently commented out)."

The first two statements are used to test the code. 1). a null string, (The string giving problems), 2), a numbered list. The numbered list will work. Moreover, the commented out statement that specifies "[_OFNBRindex]" also errors out.

What am I missing for the IF's condition that will stop null arrays so that they use the 'else' statements?

var _OFNBR = ""; // test value #1
// var _OFNBR = "100\n2\n\n40";  // test value #2

var _OFNBRindex = 0;

_OFNBR = _OFNBR.replace(/^[ \r\n\v\t\f\uFEFF\xA0]+|[ \r\n\v\t\f\uFEFF\xA0]+$/gi, "");
var _OFNBRLst = _OFNBR.match(/[0-9]+/g);

var _debug_text_msg = "Info: The DATA DUMP ref code: " + "idx " + "\"" + _OFNBRindex + "\"" + "\"" + _OFNBRLst + "\"";
java.lang.System.out.println(_debug_text_msg);

if ((_OFNBRLst !== undefined) || (_OFNBRLst !== "null") || (_OFNBRLst !== "") || (_OFNBRLst !== null)) {

  var _debug_text_msg = "Info: The NOT NULL ref code: " + "idx " + "\"" + _OFNBRindex + "\"" + "\"" + _OFNBRLst + "\"";
  //var _debug_text_msg = "Info: The NOT NULL ref code: " + "idx " + "\"" + _OFNBRindex + "\"" + "\"" + _OFNBRLst[_OFNbrindex] + "\"";
  java.lang.System.out.println(_debug_text_msg);

} else { // OFNBRLst is null, set to null

  var _debug_text_msg = "Info: The IS NULL ref code: " + "idx " + "\"" + _OFNBRindex + "\"" + "\"" + _OFNBRLst + "\"";
  java.lang.System.out.println(_debug_text_msg);

} // end if for OFNBRLst being null

_OFNBRindex++; // increment the _OFNBR index list.


// results

// First statement test #1

// Info: The DATA DUMP ref code: idx "0""null"
// Info: The NOT NULL ref code: idx "0""null"

// Second statement test #1
// Info: The DATA DUMP ref code: idx "0""100,2,40"
// Info: The NOT NULL ref code: idx "0""100,2,40"

Solution

  • It looks like you just have some ORs where you would need ANDs (if you needed those other !== checks). However, the return value for String.protoype.match which you're using is either an array (if matches are found) or null. So you don't need any of your !== string checks.

    So change this line:

    if ((_OFNBRLst !== undefined) || (_OFNBRLst !== "null") || (_OFNBRLst !== "") || (_OFNBRLst !== null)) {
    

    to this:

    if (_OFNBRLst !== null) {