4:0 Making loops

Loops are amazing...

This leverages the real strength of computers - the ability to do a task many many times, very quickly.

What is a loop

In JavaScript there are lots of ways of looping through code. A loop is a way of doing something lots of times, that way code can do a lot of work for you.

Mozilla lists the types of loop you can do here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

Storing the x position

The simplest kind of loop to start with is the for loop. Its a bit more to type, but it spells out exactly what its doing:

for (let step = 0; step < 5; step++) {
  // Runs 5 times, with values of step 0 through 4.
  console.log("We have walked " + step + " steps.");
}

// This bit of code will print out:
// We have walked 0 steps.
// We have walked 1 steps.
// We have walked 2 steps.
// We have walked 3 steps.

The for loop has the following components:

  • We make a new variable, above we have used step, often for brevity we use i.
  • Then we have a conditional to decide whether we should run the loop, this is exactly like an if statement.
  • Then we tell the loop what to do after each iteration, often we increment by one. ++ means increment by 1, we could say step += 2 if we wanted to.

Using a loop to make multiple things

We could use a loop to make lots of circles. In the code below we use the normal method of creating a circle, but we can change its position by using i.

We have told the loop to start i at zero, then make it increment by 1 each time.

The conditional in the loop says keep going if i is less than 11. So i will go through 0 to 10 (making 11 circles)

Using loops to make a grid

A we saw a little earlier a loop can make a line of circles. We were looping and moving in the x direction. What if we put a loop inside a loop. That way one loop goes in the x direction to make a row, then another loop creates multiple rows in the y direction.

Have a look at the example here. The variables in the loops have been named x and y to make things easy when we use the variables.

In this code the outer y loop will run multiple times, each time it runs an inner x loop is run, this will have to complete (and make a row) before the next iteration of the y loop runs.

For loops - looping to create complexity

For loops - looping to create complexity