Home › Learn › JavaScript › Arrays

Iterating arrays

Lesson 17 of 40. for...of, forEach, and entries.

for (const item of items) visits every value and is the loop to reach for. items.forEach((item, index) => { ... }) does the same with a callback and gives the index too. for (const [i, item] of items.entries()) gives both in a for...of. Avoid for...in on arrays; it iterates keys as strings and includes surprises.

Summing, counting, and collecting are the three shapes: an accumulator declared before the loop, updated inside, returned after.

const names = ["Ann", "Ben"];
for (const [i, name] of names.entries()) {
  console.log(`${i + 1}. ${name}`);
}
// 1. Ann
// 2. Ben

Your task

Write total(prices) adding up an array of numbers with a loop, and numbered(names) returning an array of strings like "1. Ann", "2. Ben".

Hint 1

let sum = 0; for (const p of prices) sum += p; return sum;

Hint 2

for (const [i, name] of names.entries()) result.push(`${i + 1}. ${name}`);

Show the solution
function total(prices) {
  let sum = 0;
  for (const p of prices) {
    sum += p;
  }
  return sum;
}

function numbered(names) {
  const result = [];
  for (const [i, name] of names.entries()) {
    result.push(`${i + 1}. ${name}`);
  }
  return result;
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.