Chapter 5. Loops

In Lesson 3, you learned how functions can greatly clean up your code by encapsulating repetitive operations and calculations to use throughout the application's code. There are times, however, when a function isn't the right tool for handling repetitive code.

For example, you want a particular line of code repeated 10 times — no more and no less. You can, of course, write that same line of code 10 times, but in doing so you condemn yourself to a maintenance nightmare in which you may have to make 10 changes to 10 lines of code. Functions don't solve the problem either. Although the code might be a little less complex, you still have to type (or copy and paste) 10 identical lines of code.

For this reason, programming languages have a concept called looping. In programming, looping means to repeat one or more lines of code while a particular condition is true. This functionality is useful, and you'll see loops used throughout the book. But for now, let's take a look at some loops.

LOOP BASICS

There are several different types of loops, but they all perform the same primary function of repeating code. They also share some similar features. For example, all loops repeat a code block based on the results of a condition. As long as the condition evaluates to true, the loop iterates, or repeats its code, and it immediately ends when the condition evaluates to false.

Loops can be grouped into two categories: pre-test and post-test. A pre-test loop tests its condition at the ...

Get JavaScript® 24-Hour Trainer 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.