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:
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I don't necessarily think that
forloops are inherently easier to read thanwhileloops, but I think if you're doing a typical incrementing/decrementing-iterator-variable loop it probably makes more sense to useforsince that's the reasonforexists.I'll typically only use
whileif 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:tokenizetries 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 thewhileloop the correct tool for the job in this particular case. That's my thinking anyway.