Web Development · Module 5 · Lesson 51 min read

Loops & Array Methods

Loops

JavaScript
for (let i = 0; i < 3; i++) { ... }     // counting
for (const item of items) { ... }       // values of an array (best for arrays)
for (const key in obj) { ... }          // keys of an object
while (condition) { ... }

break exits a loop and continue skips to the next round.

Array methods: the modern way

They don't change the original array (except sort, reverse and splice):

MethodReturnsExample
mapa new array, each item transformedprices with tax
filterthe items that pass a testin-stock products
findthe first match (or undefined)user by id
some / everytrue or falseany or all match
reduceone combined valuetotal of a cart
forEachnothing; just runs codelogging
sortsorts in placeneeds a compare function for numbers
JavaScript
const total = cart
  .filter((item) => item.inStock)
  .map((item) => item.price * item.qty)
  .reduce((sum, n) => sum + n, 0);

⚠️ [10, 2, 1].sort() gives [1, 10, 2] because it sorts as text by default. Use .sort((a, b) => a - b).

💡 To sort without changing the original, use toSorted() in modern browsers, or [...arr].sort().

Example

JavaScript
const products = [
  { name: "Pen",    price: 20,  inStock: true },
  { name: "Book",   price: 350, inStock: true },
  { name: "Bag",    price: 900, inStock: false },
];

const names = products.map((p) => p.name);
const available = products.filter((p) => p.inStock);
const book = products.find((p) => p.name === "Book");
const total = available.reduce((sum, p) => sum + p.price, 0);
const cheapestFirst = [...products].sort((a, b) => a.price - b.price);

console.log(names);                    // ["Pen", "Book", "Bag"]
console.log(available.length, total);  // 2 370
console.log(book.price);               // 350
console.log(cheapestFirst[0].name);    // Pen
console.log(products.some((p) => !p.inStock));   // true