Teacher’s Guide

Looping Lists

Main Goal

This lesson focuses on learning how to iterate through a list in JavaScript. This lesson assumes the students are already comfortable with creating, accessing, adding, and removing elements in a list.

Learning Objectives

Students will be able to:

Write code that can:

  1. Iterate through a list of items with a start and end index using a for loop
  2. Search through a list of items for a value using a while loop

Key Terms

Iterate: Literally means ‘to do again’. In computer science, this is commonly refers to the act of moving through a list or set of items.

Array: Another name for a list in JavaScript.

Agenda

Presentation (10-20 minutes)

Use the presentation, and go over how to iterate through a list.

Using a for loop

If you have a list with a lot of items, and you need to do something with them, it can be a pain to go through them one by one:

var list = [4, 6, 7, 4, 10];

function sumList(){
   
return list[0]+list[1]+list[2]+list[3]+list[4];
}

Notice that as we go through the list, the index we use goes up by one, so we could easily set up a for loop to count the same way:

for(var i = 0; i < 5; i++){
   
//do something with list[i];
}

Query the class for a solution to complete this function to correctly calculate the sum.

Solution

function sumList(){
   
var sum = 0;
   
for(var i = 0; i < 5; i++){
       sum += list[
0];
   }
   
   
return sum;
}

And although we know the length of this list is 5, note that it is better to use

list.length

So that it will always correctly iterate through the whole list regardless of its size (even if it’s empty!).

Illustration

If students are having a hard time following the slides, ask 5 students to come to the front of class and stand in a line to represent a list. Use index cards to represent either their index in the list or their value.  Step through array one step at a time, following the steps of the for loop.

You can use console.log() instead the sum, and whenever you get to it, have the student say their name or the value they are ‘holding’ out loud.

Activity (15 minutes)

Hand out the worksheets, and walk around the room helping students as they need it.

Solutions

Question 1:

Question 2:

Jim
6
Strawberry
6.7
Music

Music
6.7
Strawberry
6
Jim

Challenge

var max = list[0];
var min = list[0]; //optional

for(var i = 1; i < list.length; i++){
   
if(list[i] > max){
      max = list[i];
   }
   
if(list[i] < min){  //optional
      min = list[i];
   }
}
//max will be maximum value in list
//min will be minimum value in list

Resources

Java script arrays overview:

https://www.w3schools.com/jsref/jsref_obj_array.asp

Mozilla documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Looping through arrays:

https://www.youtube.com/watch?v=RXWO3mFuW-I