Search⌘ K

Iterating Arrays

Explore how to iterate arrays in JavaScript by using for loops, while loops, nested loops, and the forEach method. Understand indexing, looping directions, and practical ways to access elements in both single and multi-dimensional arrays.

In this lesson, we will see how loops iterate arrays, where iterate means accessing elements in the array one by one.

Iterating single-dimensional arrays

To iterate a single dimension array, we design a loop that will index each element and terminate when the end is reached. Take for example the following array:

var arr = [ 10, 25, 7, 100, 20 ];

To iterate it, we start off with the first element (index 0) and end at the last element (index 4).

Notice a couple of things:

  1. The indexing starts from 0.
  2. The index in each iteration is incremented by one.
  3. The indexing stops at the last index, which is always one less than the length of the array.

With these observations in mind, use the for loop to iterate arr as shown below.

Node.js
var arr = [10, 25, 7, 100, 20]; // initialise arr
// iterate array from start to end
for(var i = 0; i < arr.length; i++){
console.log(arr[i]);
}
console.log("indexing complete");

In the above code, we use the for loop to iterate the ...