Loops & Array Methods
Loops
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):
| Method | Returns | Example |
|---|---|---|
map | a new array, each item transformed | prices with tax |
filter | the items that pass a test | in-stock products |
find | the first match (or undefined) | user by id |
some / every | true or false | any or all match |
reduce | one combined value | total of a cart |
forEach | nothing; just runs code | logging |
sort | sorts in place | needs a compare function for numbers |
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
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