2

I've been reading JavaScript: The good parts. Theres a section: The Bad Parts. This is straight from the book:

continue Statement
The continue statement jumps to the top of the loop. I have never seen a piece of code that was not improved by refactoring it to remove the continue statement.

So my question is, is there ever a situation continue is required?

  • 4
    Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. Douglas Crockford is a _very_ opinionated person. Personally - I don't like `continue` either but that's completely subjective. – Benjamin Gruenbaum Feb 22 '14 at 22:23
  • Totally agree with @BenjaminGruenbaum here is another post that discusses this for many cases: http://stackoverflow.com/questions/7973115/when-to-use-the-continue-keyword-c-sharp – CodeBird Feb 22 '14 at 22:30

3 Answers3

2

There are strong opinions on both sides, wether continue is useful or not. But it is never required. You can always find a way around it, if you want.

zord
  • 4,538
  • 2
  • 25
  • 30
0

There are some believe that if there is a continue in your loops, that it should probably be refactored or rewritten. There are legitimate uses of continue, but they can usually be avoided. To give an example:

   for (var i = 0; i < particles.count(); ++i)
   {
     if (OutOfBounds(particles[i])) {
        RemoveFromArray(particles[i]));
        ++i;
        continue;
     }
   }

In this case, the continue is unnecessary because there is nothing else in the loop, but it would be if you were to do something else after the initial check.

Also, it helps with readability, if you have a complicated loop with nested conditionals. For example, you may have a bunch of extraneous variables like quitLoop1 and quitLoop2 and so on.

  • 1
    `particles.filter(function(particle){ return !OutOfBounds(particle);})` is a _lot_ cleaner and does the same thing. Then you just loop through that. – Benjamin Gruenbaum Feb 22 '14 at 22:40
  • 1
    Also, the question was: "is there ever a situation continue is required?" and you didn't really answer that. – zord Feb 22 '14 at 22:41
0

In my experience, the continue statement is useful if a condition in a loop is met, and you don't want to execute the rest of the code in the loop on that iteration. The reason why you'll get mixed opinions on its usefulness is that many will argue there are better ways to rewrite your code so you don't have to use it. In my opinion that argument is strictly for readability purposes.

I have never used continue in javascript because most of the javascript I write is simple DOM manipulation. However, I have used continue in various Python programs, and it can be useful (as mentioned above) to skip over the loop under certain conditions.

samrap
  • 5,595
  • 5
  • 31
  • 56