AI Features

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:

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 ...