My question is, wouldn't this code still execute properly without the return? Just trying to wrap my mind around its purpose. I notice serveral other places have the same setup, like when we create enemies.
This return simply means: quit the function here. The whole code means: If the enemy is outside of the screen at the left side then delete it and don't do any other tests (collision and shooting)
no the .each() function is not aborted after a call to return, just the call to the function in for one of the element from the set on which you called the .each() function.
I think I'm getting it now. we're not trying to abort the .each() function, we're simply aborting the current element that is in place, and the best way to do that is to use return; which then allows the .each() function to keep going for the next element?
I just tested out everything we talked about and now I understand that if we don't use return at all, it throws a null error. But here is the funny thing..when I use return false inside of the conditional statement, it works the same as return; and doesn;t cancel the .each() function loop. It removes the enemy selector from the DOM when he goes pass the screen and doesn't throw any errors in the web console. So it appears at the moment that return false; works just as good as return; I'm testing this out in Google Chrome, IE9 and FireFox 15
here is my version of the code...
/*FOR EACH ENEMY...*/ $(".enemy").each(function(){
/*Update with player group (required)*/ /*If enemy travels off screen, remove from DOM*/ this.enemy.update($("#player")); mthis = $(this); var posx = mthis.x(); if(posx < 0){ mthis.remove(); return false; } .... });
I know that is what "should" happen. But if you test it out yourself, and place return false there in your demo 3 game, you will see that the enemy ships will still continue to come out and then remove themselves from the DOM when the leave the screen. So my question is, how can we test that the each() loop stopped iterating?
I just realized that return; is the same as making the item return undefined, which is is the same as saying it no longer exist which is what we want once the enemy goes off screen! still kinda odd how the .each loop will continue to spit out enemies with a return false; at te end, but besides that, the base understanding of my original question is clear now.