Iteration: the for-loop

By now, we have many tools to let us do stuff with JavaScript: change with jQuery, add to the page with jQuery, draw and animate shapes with Raphaël. The problem is that we have to write code to every change separately.

We want the programming language to help us: let us express the things we need to do as concisely as possible. We also need to be able to repeat pieces of code some number of times (that we might not know exactly when writing the code).

The iteration (or repetition or looping) structures that we'll learn here will help us do just that: repeatedly execute a piece of code.

The for Loop

The for loop in most programming languages (including JavaScript) is used when you have a “definite” number of times to iterate: you know at the start of the loop that you want to repeat 10 times (or n times with a value in a variable).

Repeating 10 times is done by basically asking JavaScript to count from 1 to 10 (or 0 to 9 or something). The syntax for the for loop in JavaScript is a little ugly: there's a lot of punctuation. On the bright side, it's a very common idiom and will always look the same.

This code will count from 1 to 10, and add a paragraph to the id="example1" element on the page each time it counts:

for (step = 1; step <= 10; step += 1) {
  $('#example1').append('<p>One more paragraph.</p>')

Here's what's happening there:

for ( … ) { … }
This is the basic structure of the for loop. The stuff in the ( … ) controls the loop, and the { … } is the code that repeats.
(…; …; …)
There are three pieces that control the loop: where to start, the condition to keep going, and how to count.
step = 1
This is how the loop starts: by setting the variable step to one. This variable is the loop counter.
step <= 10
The loop will continue as long as this condition is true: step is less than or equal to 10. That is, we will count up to 10.
step += 1
This is an instruction about how to count. The += means “add to the variable”, so we're counting by ones here. This code is equivalent to step = step + 1. You may also see this written step++ which means “add one”.
{ … }
This is the loop body. This code will run with the variable step equal to 1, then to 2, 3, 4, … 10.

The result: the three lines of code will add 10 paragraphs to the page.

Realistically, this loop will always look the same, except you can change the variable name (from step to anything descriptive); change the start/end value for the loop (1 and 10 in the example, but can be anything); change the body of the loop to do the actual work you need to do.

Another Example

Here's another example. In this code, we're counting from 1 to 6, and actually using the value in the counter variable n as part of the paragraph.

for (n = 1; n <= 6; n += 1) {
  $('#example2').append('<p>Paragraph #' + n + '</p>')

The code in the loop body here does some work to create the string that is appended. It joins the string '<p>Paragraph #' with the value in the variable n and the string '</p>'. The result is that it will add these paragraphs to the page:

<p>Paragraph #1</p>
<p>Paragraph #2</p>
<p>Paragraph #3</p>
<p>Paragraph #4</p>
<p>Paragraph #5</p>
<p>Paragraph #6</p>

With Raphaël

We can do anything we want in the body of the for loop. In this example, we will draw some shapes using Raphaël.

We'll start by creating the paper object outside of the for loop (because we only need one of them, not twelve) and creating some variables that we'll need inside the loop (since they're the same each time, there's no need to recreate them many times). Then each time around the loop, we'll draw two things:

paper = Raphael('container', 400, 200)
circle_attrs = {
  'stroke': '#c50',
  'stroke-width': '2'
rect_attrs = {
  'fill': '#292',
  'stroke-width': '1.5'
for (count = 0; count <= 11; count += 1) {
  c = + count*14, 20 + count*12, 6)
  r = paper.rect(250, 100, 40, 40)
  r.scale(3 - count*0.25)

In the loop, we first draw a circle, calculating its position based on the loop counter count. Then we draw a rectangle, with rotation and scaling calculated from count.

In this loop, we started counting from 0 to 11 (instead of 1 to 12). I found the calculations easier to think about that way, but the loop runs 12 times either way. The result is this:

Result of for-loop and Raphaël
Result of for-loop and Raphaël

You can also look at the page with all of these examples to see exactly how they work.

In some ways, this might be where programming starts to pay off: finally we can have the computer do work for us, rather than having to give every instruction very manually. Particular when we pair with Raphaël, we can get interesting results in relatively little code.