For loop patterns

The primordial for loop

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

You should be able to look at this and immediately know that it executes 100 times.

A counting for loop

let count = 0;
for (let i = 0; i < 100; i++) {
  if (someCondition(i)) {
    count++;
  }
}
// count is now the count of times someCondition was true

A summing for loop

let sum = 0;
for (let i = 0; i < 100; i++) {
  sum = sum + something(i);
}
// sum is now the sum of all the values returned by something

A finding for loop

// In the context of a function so we can use return
for (let i = 0; i < 100; i++) {
  if (someCondition(i)) {
    // Found it
    return true;
  }
}
// If we get here we didn't find what we were looking for
return false;

Nested for loops

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

Up next

Arrays