These patterns should be familiar.
for
loop over an arrayfor (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
.
for
looplet 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
for
looplet 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
for
looplet 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.
for
looplet 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.
for
loopconst 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
for
loopFind 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;
};
for
loopIs 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;
};
for
loopIs 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;
};