Code Highlights logo

Learn

Loops

Looping through Arrays

For Loop: One of the most common ways to loop through an array is by using a for loop. The for loop allows us to define a variable that will act as the index, the condition for the loop to continue, and the statement to increment the index.

1for (let i = 0; i < arr.length; i++) {
2 // access the elements using arr[i]
3 // perform any desired operations
4}

For...of Loop:

Another way to iterate through an array is by using the for...of loop. This loop simplifies the code by directly accessing each element of the array without the need for an index.

1for (let element of arr) {
2 // access the elements using 'element'
3 // perform any desired operations
4}

The for...of loop is particularly useful when you only need to access the elements of the array and don't require the index.

Example

Let's consider an example to illustrate how to loop through an array. Suppose we have an array of numbers:

1let numbers = [1, 2, 3, 4, 5];

We can loop through this array using a for loop and log each element to the console:

1for (let i = 0; i < numbers.length; i++) {
2 console.log(numbers[i]);
3}

This code will output:

11
22
33
44
55

Similarly, we can achieve the same result using a for...of loop:

1for (let number of numbers) {
2 console.log(number);
3}

The output will be the same as before.


Instructions

1.

Replace the existing TODO comment, write a for loop that iterates through the whole numbers array.

2.

Within the loop, log each number to the console.

Sign up to start coding

Already have an account?

Sign In

Course content