01 / 06
Loops, and where your data lives
INPUT · Slides
Running a loop over the nesting
02 / 06
Use i as the number
Use the i from your for as the array number and join .name onto the end.
Read list[i].name as "the name of entry i".
const pets = [ { name: "Mofu", age: 3 }, { name: "Pochi", age: 5 }, { name: "Tama", age: 1 },];for (let i = 0; i < pets.length; i++) { console.log(pets[i].name);}Result
Mofu Pochi Tama
03 / 06
Catching one at a time reads better
When pets[i].name turns up over and over it gets hard to read. Catch it once inside the { } and it reads far better.
Either way behaves the same. Choose whichever reads better.
const pets = [ { name: "Mofu", age: 3 }, { name: "Pochi", age: 5 },];for (let i = 0; i < pets.length; i++) { const pet = pets[i]; console.log(`${pet.name}: age ${pet.age}`);}Result
Mofu: age 3 Pochi: age 5
04 / 06
Adding it all up
Put the piling variable outside and you get the total across every entry. However many there are, the code is the same.
Mix in an if and you can "count only the ones that match". This is where every tool you have learned joins up.
const cart = [ { name: "bread", price: 160, count: 2 }, { name: "seaweed", price: 220, count: 3 },];let total = 0;for (let i = 0; i < cart.length; i++) { total += cart[i].price * cart[i].count;}console.log(total);Result
980
05 / 06
Counting only what matches
Put an if inside the loop and you can count or pile up only the entries that match, like "how many are out of stock".
const items = [ { name: "bread", stock: 0 }, { name: "seaweed", stock: 5 }, { name: "water", stock: 0 },];let outOfStock = 0;for (let i = 0; i < items.length; i++) { if (items[i].stock === 0) { outOfStock++; }}console.log(`${outOfStock} out of stock`);Result
2 out of stock
06 / 06
Finding the highest value
"Which one is the most expensive?" fits the same shape. Keep a variable holding the current best and swap it in whenever something bigger turns up.
Starting from the first entry is the trick — start from 0 instead and it breaks if every price happens to be negative.
const prices = [ { name: "bread", price: 160 }, { name: "seaweed", price: 220 }, { name: "water", price: 90 } ];let highest = prices[0];for (let i = 1; i < prices.length; i++) { if (prices[i].price > highest.price) { highest = prices[i]; }}console.log(highest.name);Result
seaweed