; PSY 1903
PSY 1903 Programming for Psychologists

Loops

Looping through arrays

A key technique in programming is making something repeat using loops. A common type of loop is the for loop. Here’s an example looping through an array of items in JavaScript:

let items = ['apple', 'banana', 'cherry', 'date', 'fig'];

for (let item of items) {
    console.log(item);
}

Output:

apple
banana
cherry
date
fig

Numerically looping

In addition to looping through an array, you can define a numerical for that starts at some number and continues until some end point.

for (let i = 0; i < 6; i++) {
    if (i % 2 == 0) {
        console.log(`${i} is an even number`);
    } else {
        console.log(`${i} is an odd number`);
    }
}

Output:

0 is an even number
1 is an odd number
2 is an even number
3 is an odd number
4 is an even number
5 is an odd number

When defining a numerical for loop, you construct the loop using three expressions:

  1. Define a “cursor” variable that will iterate through the loop, indicating its start value: let i = 0
  2. Define a Boolean expression that once True, will terminate the loop: i < 6
  3. Define how the cursor should change each iteration through the loop: i++

In this example, we named our “cursor” variable i which is short for iterator. This naming convention is commonly used across many different programming languages, but it's not required. You can name your cursor variable whatever you want, as long as it’s a valid variable name.