Loops Can Nest

Just as you can nest if-then statements inside other if-then statements, you can also put loops inside other loops. For example, Figure 8-15 shows you a script that writes a solid rectangle of Xs to a web page, five Xs high and ten Xs wide (see the result in Figure 8-16). Although this script doesn't do anything useful, it offers an idea of how nesting loops work.

A simple example of nesting loops

Figure 8-15. A simple example of nesting loops

Line ❶ in Figure 8-15 sets up a loop that will be executed five times. Each time through that loop, the second, or inner, loop (❷ and ❸) runs. That loop writes the letter X to the web page ten times. After the inner loop has run, ...

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.