1

I have the following code:

var linesMissingDelim = [];
var linesMultipleDelims = [];
var rawLines = rawWordsTxt.split(new RegExp('\r\n?|\n'));
rawLines.forEach(function (rawLine, index){
    var parsedLine = rawLine.split(delim);
    if(parsedLine.length-1 === 1){
              oWords.lang1list.push(parsedLine[0]);
              oWords.lang2list.push(parsedLine[1]);
    }
    else if (parsedLine.length-1 === 0){
             linesMissingDelim.push(index+1);
    }
    else {
            linesMultipleDelims.push(index+1);
    }
});

if (linesMissingDelim === [] && linesMultipleDelims === []){
    doSomething(); //the file is valid, do stuff
}
else {
    if (linesMissingDelim.length > 0){
           doSomething1(); 
    }
    if (linesMultipleDelims.length > 0){
           doSomething2();
    }
    doSomething();
}

I was testing this code and opened some valid test files, but the program incorrectly executed the else branch (that contains two if checks that check if which of the arrays is empty) and complained that the files were invalid. So I debugged the problem with the Firefox Debugger: the last else branch was executed (because the if branch with the && didn't evaluate to true somehow), but neither of the 2 small if statements in the else branch evaluated to true! Weird right? How can the 2 arrays not be equal to an empty array ([])(and therefore have a length larger than 0), but their lengths be 0? I verified that the 2 arrays indeed stayed empty: they both showed up as 'Array[0]' in the FF debugger.

Then I replaced:

linesMissingDelim === [] && linesMultipleDelims === []

with:

linesMissingDelim.length === 0 && linesMultipleDelims.length === 0

And now suddenly the code does work correctly!

So basically my question is how can

anArray === [] -> false

when:

anArray.length === 0 -> true

and anArray is literally defined as []?

Superpelican
  • 85
  • 1
  • 8
  • You could use if (!linesMissingDelim[0] && !linesMultipleDelims[0]) – Dom Slee Jul 19 '15 at 12:39
  • @D Slee I have already fixed it by the checking if the length is 0. I only have to check if the arrays contain anything. I just asked this question to *understand* this behaviour. ;) But [this 'duplicate'](http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript) answers my question. Though I do believe this question is useful, because I couldn't find that 'duplicate' when searching SO. – Superpelican Jul 19 '15 at 12:44

0 Answers0