5.3 Iterating Through Arrays

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.


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?
  • We create an array with values: 1, 2, 3, 4.
  • We then used a for loop that is set to stop after i < arr.length (the length of the array).
  • At each iteration, we console.log() the value found at that certain index in the array.

Alternative Example

We can actually use a for each loop to accomplish the same thing!
let arr = [1, 2, 3, 4]; arr.forEach((num) => { console.log(num); }); // output: // 1 // 2 // 3 // 4


You can add practice problems here if you want. Follow the format below.
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.