The food log is a list. To get today’s total, you need to visit every item and add up the calories. That’s a loop.
JavaScript gives you several ways to do it. They’re not competing religions — each one fits a different job.
The classic for loop
for (let i = 0; i < foods.length; i++) {
console.log(foods[i].name);
}
Three parts: start at 0, keep going while i < length, add 1 each time. It’s flexible, but the index bookkeeping is noise when you just want the items.
for…of
let total = 0;
for (const food of foods) {
total += food.calories;
}
console.log(total);
This reads as “for each food in foods.” No index, no off-by-one. Use it when you need to loop and maybe break early.
forEach
let total = 0;
foods.forEach((food) => {
total += food.calories;
});
forEach runs a function for each item. It’s fine for side effects like logging. It does not return a new array, and you can’t break out of it.
map, filter, find
You met these last lesson. Quick recap:
const names = foods.map((food) => food.name);
const highProtein = foods.filter((food) => food.protein >= 20);
const chicken = foods.find((food) => food.name === "Chicken and rice");
They’re the cleanest way to transform and select.
reduce: the total machine
reduce turns an array into a single value: a total, an average, an object, anything.
const totalCalories = foods.reduce((sum, food) => {
return sum + food.calories;
}, 0);
Read it as:
sumis the accumulator — the running total.foodis the current item.0is the starting value.- Whatever you return becomes the next
sum.
For a total, always pass the 0. Without it, reduce starts with the first item and can behave strangely on an empty array.
const totalProtein = foods.reduce((sum, food) => sum + food.protein, 0);
That’s the whole pattern. Once it clicks, you’ll see it everywhere.
Try it
Console
Console is quiet. Run the code to see output.
Edit the code, then hit Run (or Ctrl + Enter) and watch the console. This is a safe sandbox — you can't break the page.
Add up the day
the plan's verify stepUsing the food array, calculate the total calories and total protein with reduce. Then count how many foods are over 400 calories. Finally, find the food with the most protein.
For the highest-protein food, you can sort a copy or loop through and keep track of the current winner. Don't mutate the original array.
The mistakes everyone makes
for...inon an array. It loops over keys as strings. Usefor...ofor a classicfor.- Off-by-one.
i <= foods.lengthreads one item past the end. Use<. - Forgetting the initial value in
reduce. Always pass0for sums. - Returning nothing from a
mapcallback. You’ll get an array ofundefined. - Mutating the original array.
filterandmapreturn new arrays; use them. - Using
forEachwhen you need a return value. It always returnsundefined. - Nested loops for a simple lookup. Use
find.
for...of is the readable way to loop over array items.
forEach runs a function per item but returns nothing.
map transforms, filter selects, find gets the first match.
reduce turns an array into one value; pass 0 for totals.
Don't mutate the original array when a method can return a new one.
Next: the DOM. We’ll stop logging to the console and start changing the actual page.
Up next
The DOM: select, read, change
The DOM is the browser's live model of your HTML. Learn to select elements, read their values, change their text and classes, and create new elements.