Iteration through Arrays
Sometimes we want to go through the elements of an array one by one. We can achieve this using a for
loop.
Such a for
loop might look like this:
const games = ["Soccer", "Tennis", "Golf"];
for (let i = 0; i < games.length; i++) {
console.log(games[i]);
}
This prints:
Soccer
Tennis
Golf
This loop runs as long as i
is less than the length of the array, and in each iteration, it prints the array element at index i
. Since i
starts at 0
and ends at a value less than the number of elements in the array, it goes through all the elements of the array and prints them using console.log(games[i]);
.
In JavaScript, there is an even simpler way to achieve this:
const games = ["Soccer", "Tennis", "Golf"];
for (const element of games) {
console.log(element);
}
This prints:
Soccer
Tennis
Golf
Here we have an iteration variable element
, but we can name it anything. After this element follows the word of
and the name of the array variable. This syntax stores the value of the corresponding array element in the element
variable during each iteration.
The downside of this syntax is that it can only be used when we want to go through all the elements of the array. With the standard syntax, we can iterate backward, skip elements, or start at a chosen index.
Instructions
Using any for
loop syntax, iterate through the teammates
array and print each element of the array.
Start programming for free
4/9