5.3 Iterating Through Arrays

Iterating Through Arrays

There are different ways to iterate through arrays.

All you need to choose a loop that best fits your needs.

Practice will help you determine what kind of loop you would want for a certain problem.

The general idea is that some kind of 0 based index is given to the array to return the value found in that location of the array.

The 0 based index would then be increased by a certain amount over a certain period of iterations.

Example

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

// output:
// 1
// 2
// 3
// 4

What is happening here?

Alternative Example

<aside> 💡 We can actually use a for each loop to accomplish the same thing!

</aside>

let arr = [1, 2, 3, 4];
arr.forEach((num) => {
	console.log(num);
});

// output:
// 1
// 2
// 3
// 4

Practice

You can add practice problems here if you want. Follow the format below.