...

/

Iteration over Sequences Using a foreach Loop

Iteration over Sequences Using a foreach Loop

Learn how to iterate over a list of items using the foreach loop.

The foreach loop

If we have a sequence of things (for example, an array) it can be handy to go through that sequence one item at a time. We do have a loop for that too, which is the foreach loop.

When we have a sequence of things, we often want to go through it item by item. We can, of course, do that using a for loop, like this:

Press + to interact
names = ["Anna", "Bob", "Carl", "Danielle"]
for i = 0 to names.length
print "Hi " + names[i]

On line 1, we declare an array of strings containing some names. We’re using a variable called names to store these values.

Then, we use a for loop, starting at 0. To find out how many times we’ll iterate, we ask the array how many items it currently has stored. We do that by using the names variable; by using a period after that, we can get what is known as a property ...