I have the following code
if (msg.position == 0)
//removed for brevity
else if (msg.position == txtArea.value.length)
//removed for brevity
else {
//ERROR: should not reach here.
errorDivTag.innerHTML += msg.position + " " + txtArea.value.length;
}
I’m having some really weird situations where I’m getting the error in the last code block, but the printed positions show that msg.position is in fact equal to the txtArea.value.length. This only happens 1% of the time, almost as if I have some kind of race-condition in my code where the two are NOT equal during the second if statement, but equal when I print in the error message.
Any ideas?
To start with, always use
===. That will prevent JavaScript from automatically coercing the types in the comparison, which means you’ll be able to spot all sorts of bugs much more easily. In this case, it’s possible you have some whitespace (which is basically impossible to see in the output) that is causing a string comparison instead of the (I assume) desired numeric comparison.Also, I’m assuming you really meant to have
{after yourifandelse ifconditions. If not, that could be causing all sorts of strange behavior, depending on the code you removed due to brevity concerns. If you didn’t, then you’ve got an extraneous}before yourelsecondition.UPDATE: Set a breakpoint in Firebug/DeveloperTools/DragonFly/whatever and inspect the values as the comparison occurs.