The if-else
and switch
statements allow your code to take different paths, as if you're at a crossroad and decide which way to go depending on a condition. Loops, on the other hand, allow your code to take a few roundabouts before merging back into the main road. How many repetitions? That depends on the result of evaluating a condition before (or after) each iteration.
Let's say you are (your program execution is) traveling from A to B. At some point, you reach a place where you evaluate a condition, C. The result of evaluating C tells you if you should go into a loop, L. You make one iteration and arrive at C again. Then, you evaluate the condition once again to see if another iteration is needed. Eventually, you move on your way to B.
An infinite loop is when the condition is always true
and your code gets stuck in the loop "forever". This is, of course, a logical error, and you should look out for such scenarios.
In JavaScript, there are four types of loops:
while
loopsdo-while
loops...