for Loops

Another type of loop is the for loop. You format while and for loops differently, but they do the same things. Which loop you use is largely a matter of preference. Though for loops look a little more confusing at first, they are more compact.

Figure 8-10 compares a while loop and a for loop that perform exactly the same task.

Comparing a while loop and a for loop

Figure 8-10. Comparing a while loop and a for loop

Both of the loops in Figure 8-10 write the word hello to a web page ten times. The main difference between them is that ❶, ❷, and ❸ in the while loop collapse into ❹ in the for loop. The format of a for loop is as follows:

for (initializer; test; incrementer)
{
   // 

Get The Book of JavaScript, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.