O'Reilly logo

JavaScript® 24-Hour Trainer by Jeremy McPeak

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required