DEV Community

Discussion on: While vs for

Collapse
 
dannymcgee profile image
Danny McGee • Edited

I don't necessarily think that for loops are inherently easier to read than while loops, but I think if you're doing a typical incrementing/decrementing-iterator-variable loop it probably makes more sense to use for since that's the reason for exists.

I'll typically only use while if I need to check some other sort of condition that doesn't fall neatly into that pattern. As an example, I'm currently building a syntax highlighter for the web (mostly for fun), and I have a method like this:

parseLine(this.current.line) {
  while (this.current.line.length > 0) {
    this.tokenize(this.current.line);
  }
}

tokenize tries to match the beginning of the line (which is a string) for a number of different regex patterns, assigns the match a token, and then removes the match from the front of the line. So each time it's done, the line will be a little shorter, but it's impossible to know by how much ahead of time, which makes the while loop the correct tool for the job in this particular case. That's my thinking anyway.