I apologize in advance, I spent the last three hours explaining stuff and what you read now is exactly what I feel like
Dear J_F_B_M, why is there an error?
if (item);
This line does nothing. It is an empty statement. It is equal to:
if(item) {
// Do nothing
}
This is because a single ;
is a valid JS-Statement. In fact, ;;;;;
is a total of 5 statements (which all do nothing).
But J_F_B_M, there is a curly bracket behind that…
Jup, you’re right. In other languages (like Java, which looks similar but is different) this would be important. Here it isn’t (in the same way). The curly brackets enclose a block statement. A block statement encloses zero or more other statements (which can also be more block statements).
But J_F_B_M, why do you tell us this boring stuff?
You haven’t known up until now about it, but you already used block statements quite often. An if
-statement can only be followed by one other statement. But sometimes this is not enough, we want multiple statements “inside” an if. The solution: A block statement.
Come on, get to the point. What is my problem?
if (flag) {
// Bla bla
} else if (item); {
// More Bla
}
This code is equal to the following code (I added some intendations
if (flag) {
// Bla bla
} else if (item)
;
{
// More Bla (including var itemPos = item.pos;)
}
As the block statement is unimportant here we could also remove it:
if (flag) {
// Bla bla
} else if (item)
;
// More Bla (including var itemPos = item.pos;)
Now there is definitely a problem.
More Bla
is not inside the if. At some point your code will run like this:
Is there a flag? -> No, go to else
Else, is there an item? -> No, don't execute the ;-statement
Cool, "if-else" is over, so the next statement is...
"var itemPos = item.pos;"
But "item == null"... better throw a cryptic error instead.
You can see now that even though it looks like it at first you never actually check if item==null
(at least not in a meaningful way).
And why did you post that after UltCombos answer?
I started typing first, but needed longer. Also my answer is more exhaustive.