Array loop patterns

These patterns should be familiar.

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 numbers greater than 10

A summing for loop

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

sum is now the sum of all the values in numbers

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

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

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 < numbers.length; i++) {
  if (numbers[i] > 10) {
    result.push(numbers[i]);
  }
}

results is an array of all the elements of numbers greater than 10

A finding for loop

Find the first string in an array that is more than four characters long

const findFirstLong = (strings) => {
  for (let i = 0; i < strings.length; i++) {
    if (strings[i].length > 4) {
      // Found it -- return early
      return strings[i];
    }
  }
  // Didn't find any "not found" value.
  return undefined;
};

A “some” for loop

Is some element of an array greater than 10?

const someBiggerThanTen = (numbers) => {
  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;
};

An “every” for loop

Is every element of an array greater than 10?

const allBiggerThanTen = (numbers) => {
  for (let i = 0; i < numbers.length; i++) {
    // Note that the test is reversed since we are
    // looking 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;
};