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.
for
loopfor (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.
for
looplet 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.
for
looplet 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
.
for
looplet 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.
for
looplet 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.
for
loopfor (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.)
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.)
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
loopslet 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.