Chapter 17

What’s This Loop For?

for loops are useful for when you know in advance how many times you need to do something. You can use a for loop to count to 10, or to count to 1,000,000. It’s all the same to JavaScript!

In this chapter, we look at one of the most popular types of loops in JavaScript: the for loop. We use for loops to create our own weather forecasting app.

image

Introducing the for Loop

The for loop is the most commonly used type of loop in JavaScript. Here’s a sample for loop that prints out the words Hello, JavaScript! 500 times to the JavaScript console.

for (var counter = 0; counter < 500; counter++) {

    console.log(counter + ": Hello, JavaScript!");

}

Figure 17-1 shows what this code looks like when it’s run in the JavaScript console.

image

Figure 17-1: Saying “Hello, JavaScript!” 500 times.

This isn’t the most exciting use for a loop, but you can certainly see that it’s easier to use a loop than it would be to type out 500 console.log statements!

Let’s take a closer look at how to write for loops.

The three parts of the for loop

The for loop is made up of three different statements:

  • Initialization: The initialization statement declares a variable that the loop will use to keep track of how long it has been looping.
  • Condition: A Boolean expression to be ...

Get JavaScript For Kids For Dummies now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.