DEV Community

Randy Rivera
Randy Rivera

Posted on

Iterate Through an Array with a For Loop

A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a for loop.
Remember that arrays have zero-based indexing.

  • Example:
var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}
Enter fullscreen mode Exit fullscreen mode

Our condition for this loop is i < arr.length, which stops the loop when i is equal to length. In this case the last iteration is i === 4 i.e. when i becomes equal to arr.length and outputs 6 to the console. Then i increases to 5, and the loop terminates because i < arr.length is false.

  • Let's Declare and initialize a variable total to 0. Use a for loop to add the value of each element of the myArr array to total.
var myArr = [ 2, 3, 4, 5, 6];
var total = 0

for (var i = 0; i < myArr.length; i++) {
   total += myArr[i];
}
Enter fullscreen mode Exit fullscreen mode
console.log(total); will display 20
Enter fullscreen mode Exit fullscreen mode

CODE EXPLANATION:

  • i gets a value of 0;
  • The subsequent code is executed as long as i is lower than the * length of myArr (which is 5; five numbers but arrays are zero based).
  • i is incremented by 1.
  • The function adds myArr[i]'s value to total until the condition isn’t met like so: total + myArr[0] -> 0 + 2 = 2 total + myArr[1] -> 2 + 3 = 5 total + myArr[2] -> 5 + 4 = 9 total + myArr[3] -> 9 + 5 = 14 total + myArr[4] -> 14 + 6 = 20

Top comments (1)

Collapse
 
ramo profile image
ramooo

nice explaining