Loop patterns

A lot of uses of loops fall into simple patterns where we use loops to count things or build up results in some other way.

The primordial for loop

for (let i = 0; i < n; i++) {
  // code here that uses i
}

You should be able to look at this and immediately know that it executes the body of the loop n times and that i takes on the values from 0 to n - 1, inclusive.

A counting for loop

let count = 0;
for (let i = 0; i < s.length; i++) {
  if (isVowel(s[i])) {
    count++;
  }
}

count is now the number of characters in s that are vowels, assuming isVowel exists and does what we’d expect.

A summing for loop

let sum = 0;
for (let i = 0; i < n; i++) {
  sum += n ** 2
}

sum is now the sum of the squares of all the integers less than n.

A maximizing for loop

let maximum = 0;
for (let i = 0; i < n; i++) {
  maximum = Math.max(maximum, Math.random());
}

maximum is now the largest value returned by Math.random() in n calls.

A collecting for loop

let result = '';
for (let i = 0; i < s.length; i++) {
  if (isVowel(s[i])) {
    result += s[i];
  }
}

results is a string containing all the characters in s that are vowels.

An index finding for loop

for (let i = 0; i < s.length; i++) {
  if (isVowel(s[i])) {
    // Found a vowel: return the index
    return i;
  }
}

// If we get here we didn't find any vowels.
// Return some distinguished "not found" value.
return -1;

(Note: this code assumes it’s in a function from which we are returning the index.)

A “some” for loop

// Is some element of s a 'z'?
for (let i = 0; i < s.length; i++) {
  if (s[i] === 'z') {
    // Found at least one 'z'
    return true;
  }
}
// Didn't find any 'z's
return false;

(Note: this code assumes it’s in a function from which we are returning a boolean.)

An “every” for loop

// Is every element of the array a consonant?
for (let i = 0; i < s.length; i++) {
  if (isVowel(s[i])) {
    // Found a counter example -- return early
    return false;
  }
}
// Every element met our criteria
return true;

(Note: this code assumes it’s in a function from which we are returning a boolean.)

while loops

let count = 0;
while (Math.random() < 0.5) {
  count++;
}

count is now the number of times Math.random() returned a number less than 0.5 before it returned a number greater than or equal to 0.5.

while loops are most useful when we don’t know in advance how many times the loop needs to run.