For loop patterns

The primordial for loop over an array

for (let i = 0; i < array.length; i++) {
  // code here that uses array[i]
}

You should be able to look at this and immediately know that it executes once for each element of array with i taking on all the legal indices of array.

A counting for loop

let count = 0;
for (let i = 0; i < numbers.length; i++) {
  if (array[i] > 10) {
    count++;
  }
}

count is now the number of elements of array greater than 10

A summing for loop

let sum = 0;
for (let i = 0; i < array.length; i++) {
  sum = sum + array[i];
}

sum is now the sum of all the values in array

A maximizing for loop

let maximum = numbers[0];
for (let i = 1; i < numbers.length; i++) {
  maximum = Math.max(maximum, numbers[i]);
}

maximum is now the largest value from the array.

If the loop is empty numbers[0] will be undefined which is probably as good a result as any if you ask for the maximum value from an empty array.

A minimizing for loop

let minimum = numbers[0];
for (let i = 1; i < numbers.length; i++) {
  minimum = Math.min(minimum, numbers[i]);
}

minimum is now the smallest value from the array.

If the loop is empty numbers[0] will be undefined which is probably as good a result as any if you ask for the minimum value from an empty array.

A collecting for loop

const result = [];
for (let i = 0; i < array.length; i++) {
  if (array[i] > 10) {
    result.push(array[i]);
  }
}

results is an array of all the elemets of array greater than 10

A finding for loop

// Find the first element of the array
// strings longer than 4
for (let i = 0; i < strings.length; i++) {
  if (strings[i].length > 4) {
    // Found it -- return early
    return strings[i];
  }
}
// If we get here we didn't find what we were
// looking for. Return some distinguished "not
// found" value.
return undefined;

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

A “some” for loop

This code needs to be in the context of a function.

// Is some element of the array numbers greater than 10
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] > 10) {
    // Found at least one value that matches our criteria
    return true;
  }
}
// Didn't find any matches.
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 numbers greater than 10?
for (let i = 0; i < numbers.length; i++) {
  // Note that the test is reversed since we are
  // lookig for a counter example: <= 10 is
  // the same as not > 10
  if (numbers[i] <= 10) {
    // 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.)

Nested for loops

for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 4; j++) {
    // something using both i and j
  }
}