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
array
greater than 10
for
looplet 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
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 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.
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 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.
for
loopconst 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
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.)
for
loopThis 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.)
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.)
for
loopsfor (let i = 0; i < 3; i++) {
for (let j = 0; j < 4; j++) {
// something using both i and j
}
}