What are the differences between a while loop and a for loop? It seems to me that they are the same.
The
On the other hand, the
You can use them interchangeably if you like:
Or
And:
|
|||||||||||||||||
|
I just want to give a note though. Under the hood, there can be small difference. The note is that with for loop when you use it to iterate with temporary variable an array, the compiler might do loop unrolling to make sure items in the array can be pre-fetched, this will improve the performance. In javascripts, it does not matter at all. Javascripts is an interpreting language, there is no compiler. |
|||||
|
There is a fundamental difference between the two: with a Consider, for example, a program asking the user to input a series of names. Say, a patient management system for a dentist. How would you know beforehand how many patients the dentist is going to enter? You don't! You can't write a |
|||||||||
|
for
loop is just syntax sugar, supporting a subset of use cases thatwhile
supports. Sometimes "syntax sugar" is looked down upon, but it should really be looked at as a way to create cleaner, easier to understand code. – Steven Burnap Jun 9 at 16:48for
loop is actually awhile
loop in fancy clothing. – Vatine Jun 10 at 10:57