Time 1.8 hrs

Difficulty Beginner
Prerequisites Algorithms
Departments Science
Authors Sandra Kuipers
Groupings Individual
Minimum Year Group None




This work is shared under the following license: Creative Commons BY-SA-NC


Learner Outcomes
Students will:
  • ...
Competency Focus
  • ...
Interdisciplinary Connections
  • ...
What was successful? What needs changing? Alternative Assessments and Lesson Ideas? What other Differentiation Ideas/Plans could be used?
  • ...
Any CC attribution, thanks, credit, etc.

This page requires you to be logged in to access it. Please login and try again.
5 mins
Intro to Loops
Getting Started
  • Programming languages are very useful for rapidly completing repetitive tasks, from multiple basic calculations to just about any other situation where you've got a lot of similar items of work to complete.
  • Here we'll look at the loop structures available in JavaScript that handle such needs.
  • Think of loops as one more tool in your programming toolbox. They work along with other concepts you've learned.

10 mins
What is a loop?
  • Loops, loops, loops. As well as being associated with popular breakfast cereals, roller coasters, and musical production, they are also a critical concept in programming.
  • Programming loops are all to do with doing the same thing over and over again — which is termed iteration in programming speak.
  • Let's consider the case of a farmer that is making sure he has enough food to feed his family for the week. He might use the following loop to achieve this:

  • A loop usually has one or more of the following features:
    •  A counter, which is initialized with a certain value — this is the starting point of the loop ("Start: I have no food", above).
    • An exit condition, which is the criteria under which the loop stops — usually the counter reaching a certain value. This is illustrated by "Have I got enough food?", above. Let's say he needs 10 portions of food to feed his family.
    • An iterator, which generally increments the counter by a small amount on each successive loop, until it reaches the exit condition. We haven't explicitly illustrated this above, but we could think about the farmer being able to collect say 2 portions of food per hour. After each hour, the amount of food he has collected is incremented by two, and he checks whether he has enough food. If he has reached 10 portions (the exit condition), he can stop collecting and go home.
  • In pseudocode, this would look something like the following:

    loop(food = 0; foodNeeded = 10) {
      if (food >= foodNeeded) {
        exit loop;
        // We have enough food; let's go home
      } else {
        food += 2; // Spend an hour collecting 2 more food
        // loop will then run again

Loop text and graphic from Mozilla Developer Docs: Looping Code.

10 mins
Why use loops?
  • At this point, you probably understand the high-level concepts behind loops, but you are probably thinking "OK, great, but how does this help me write better code?"
  • As we saw earlier, loops help you do same thing over and over again, which is great for rapidly completing repetitive tasks.

5 mins
For Loops
  • The most versatile loop, which you'll use most of the time, is the for loop — this has the following syntax:
for (initializer; exit-condition; final-expression) {
  // code to run
  • Here we have:
  1. The keyword for, followed by some parentheses.
  2. Inside the parentheses we have three items, separated by semi-colons:
    1. An initializer — this is usually a variable set to a number, which is incremented to count the number of times the loop has run. It is also sometimes referred to as a counter variable.
    2. An exit-condition — as mentioned before, this defines when the loop should stop looping. This is generally an expression featuring a comparison operator, a test to see if the exit condition has been met.
    3. A final-expression — this is always evaluated (or run) each time the loop has gone through a full iteration. It usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the exit condition value.
  3. Some curly braces that contain a block of code — this code will be run each time the loop iterates.
  • Let's look at a real example so we can visualize what these do more clearly.

5 mins
While Loops
  • for isn't the only type of loop. Another common type of loop is the while loop.
  • This loop's syntax looks like so:
while (exit-condition) {
  // code to run
  • Unlike a for loop, there is no explicit initializer or final statement.
  • A while loop will continue to run until the exit condition is met.
  • Be careful: a while loop has a much higher chance of creating an infinite loop if the exit condition is never met!

When would you use a while loop?

  • These types of loops can be useful when you don't know how many times it will loop.
  • Consider this pseudocode for a fire alarm:
while (people are in the building) {
  ring fire alarm
  • We don't know how long it will take people to get out of the building, but we want to keep playing the alarm until everyone gets out.
5 mins
Nested Loops
  • You can do neat things when you put a loop inside another loop.
  • Consider the following code that draws a checkerboard pattern.
  • First, it loops over the x axis, then it loops over the y axis, then it draws a square.

5 mins
Infinite Loops

  • Every loop has an exit condition, but sometimes these conditions are never met.
  • A loop that never exits will continue forever! This is called an infinite loop.
  • Usually, this will crash your program, because you can't wait forever for your code to run :)
  • Consider the following while loop:
while (currentYear > 2000) {
  // code to run
  • Unless you have a time machine, the current year will never go backwards.
  • This would result in an infinite loop, because the year will never be less than 2000.

  • What are some other conditions that would result in an infinite loop?
5 mins
Breaking loops!
  • Now that you've learned how to make some loops, let's break them!
  • Most programming languages have a special command called break
  • A break statement will immediately exit the loop and move on to any code that follows it.
  • Consider the following loop that searches an array:

  • You can also skip forward inside a loop.
  • The continue statement works in a similar manner to break, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop.
  • Consider the following loop:

60 mins
Design a Pattern
  • Open up a new p5js sketch
  • Use loops to draw a pattern that repeats (consider using some nested loops)
  • Then see if you can animate your pattern to change over time.
  • Have some fun and experiment with your code!
  • Once you've made a neat animated pattern, submit your sketch as evidence of learning in this unit.
There are no records to display.
Powered by Gibbon v27.0.00dev

Founded by Ross Parker at ICHK Secondary | Built by Ross Parker, Sandra Kuipers and the Gibbon community
Copyright © Gibbon Foundation 2010-2024 | Gibbon™ of Gibbon Education Ltd. (Hong Kong)
Created under the GNU GPL | Credits | Translators | Support