Loop Through an Array

for loop

The standard for loop can be used to iterate over array items. If item index value is needed in the loop body, then you can iterate over the indices:

let dates = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

for (let i = 0; i < dates.length; i++) {
  console.log(i + ': ' + dates[i] );
}

Console results:

0: Sun
1: Mon
2: Tue
3: Wed
4: Thu
5: Fri
6: Sat

for ... in ...

Another way to loop through array is to use for index in array:

for (let i in dates) {
    console.log(i + ': ' + dates[i] );
}

This loop gives the same results as the standard for loop, but the code is a bit simpler.

for ... of...

If you don't need the index of each item, then the preferred way is to use another form of for loop: for item of array. This form produces even simpler and cleaner code:

let fruits = ["Apple", "Orange", "Banana"];

// iterates over array elements
for (let f of fruits) {
  console.log(f);
}

Console results:

Apple
Orange
Banana

Simple algorithms using for loop

With for loop we can implement a few very useful algorithms:

  • Get the sum of all numbers in a list.
  • Find the maximum/minimum item.
Get sum of all numbers

The following code calculates the sum of all numbers in an array.


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

let sum = 0;

for (let n of numbers) {
  sum += n;
}

console.log(sum);

Question: can you calculate the product of all numbers?

Find the maximum number in an array

The code to find the largest number in a list is very similar:

let numbers = [9, 4, 20, 5, 17];

let max = Number.MIN_VALUE; // This is the smallest number in JavaScript

for (let n of numbers) {
  if (n > max) {
    max = n;
  }
}

console.log(max);

Using Number.MIN_VALUE as the initial value guarantees that no item in the array can be smaller than this initial value.

Question: What can go wrong if 0 is used as initial value?

Find the minimum number in an array

Can you write the code to find the smallest number in a list?

Number.MAX_VALUE is the largest number in JavaScript

results matching ""

    No results matching ""