Get Programming with JavaScript - Listing 8.07

Listing 8.07 - Iterating over an array with forEach

var items; var showInfo; items = [ "The Pyramids", "The Grand Canyon", "Bondi Beach" ]; showInfo = function (itemToShow) { console.log(itemToShow); }; items.forEach(showInfo);

Further Adventures

Listing 8.07 - Iterating over an array with forEach - Task 1

var items; var showInfo; items = [ "The Pyramids", "The Grand Canyon", "Bondi Beach" ]; showInfo = function (itemToShow) { console.log(itemToShow); }; items.push("The Taj Mahal"); items.push("Popocat├ępetl"); items[items.length] = "The Tower of London"; items[items.length] = "Old Faithful"; items.forEach(showInfo);

Listing 8.07 - Iterating over an array with forEach - Task 2

var items; var showInfo; items = [ "The Pyramids", "The Grand Canyon", "Bondi Beach" ]; showInfo = function (itemToShow) { console.log(itemToShow + " has " + itemToShow.length + " letters"); }; items.forEach(showInfo);

Listing 8.07 - Iterating over an array with forEach - Task 3

var items; var getNumLetters; // declare a variable items = [ "The Pyramids", "The Grand Canyon", "Bondi Beach" ]; // define a function and // assign it to the variable getNumLetters = function (itemsArray) { var runningTotal = 0; itemsArray.forEach(function (item) { runningTotal += item.length; }); return runningTotal; }; // test the function console.log("Total letters = " + getNumLetters(items));