Looping Through an Array

for loops are particularly useful for looking at each item in an array. Suppose we want to print all my favorite foods from the author object. The for loop is perfect for the job (see Listing 7.16).

Listing 7.16 Looping Through an Array

for ( var i = 0; i < author.favoriteFoods.length; i++ ) {  console.log(author.favoriteFoods[i]);}

When looping through an array, the iterator i starts with 0 (the index of the first item of the array) and increases by 1 until the iterator is 1 less than the length of the array. Why stop at 1 less? Because you start with 1 (not 0) when counting the number of items in an array (the length). Confusing, right? If we used <= instead of < in the condition, we ...

Get Learning to Program now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.