NiCk Newman
NiCk Newman

Reputation: 1776

Continue Statement Confusion

The continue statement in javascript doesn't really make sense to me, or am I over thinking this?

For example, let's say I am for inning inside an object:

for (i in JM) {              
    if (JM[i].event == 'StartLocation') {
        continue;
    }
}

If that if statement is true, it's going to technically hop over that iteration. Why do we use the word continue then? Wouldn't it make more sense to use the word break? But, break does the total opposite, it stops the loop, right? (Or maybe a statement called hop) would make sense. Never really thought of this until a couple minutes ago :P

Upvotes: 0

Views: 232

Answers (3)

Bill the Lizard
Bill the Lizard

Reputation: 405735

Yes, break takes you out of the loop and places you at the line after the loop. continue takes you directly back to the start of the next iteration of the loop, skipping over any lines left in the loop.

for(i in JM)
{ // continue takes you directly here

    if(JM[i].event=='StartLocation'){
        continue;
    }

    // some other code

} // break takes you directly here

If you're only asking about the word choice, then there probably isn't a great answer to this question. Using continue does cause loop iteration to continue, just on the next iteration. Any keyword could have been chosen. The first person to specify a language with this behavior just chose the word "continue."

Upvotes: 2

Zee
Zee

Reputation: 8488

Understand it like this:

for(i in JM){
  if(JM[i].event=='StartLocation'){
        continue;
  }
  /*This code won't executed if the if statement is true and instead will move to next iteration*/
  var testCode = 3;// Dummy code
}

break will break the for loop(come out of for loop) but continue will skip the current iteration and will move to next iteration.

You will find the relevant docs Here.

Upvotes: 1

maioman
maioman

Reputation: 18734

The continue keyword is similar to break, in that it influences the progress of a loop. When continue is encountered in a loop body, control jumps out of the body and continues with the loop’s next iteration.

Upvotes: 1

Related Questions