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 []?