JavaScript · 2 min read
Arrays and Loops
Store lists of values in arrays, repeat work with loops, and transform data with map, filter, and reduce.
Arrays
An array is an ordered list of values, written in square brackets:
js
const fruits = ["apple", "banana", "cherry"];
fruits[0]; // "apple" (indexes start at 0!)
fruits[2]; // "cherry"
fruits.length; // 3
fruits[fruits.length - 1]; // "cherry" (last item)Changing arrays
js
const list = ["a", "b"];
list.push("c"); // add to end → ["a", "b", "c"]
list.pop(); // remove from end → ["a", "b"]
list.unshift("z"); // add to start → ["z", "a", "b"]
list.shift(); // remove start → ["a", "b"]
list.includes("a"); // true
list.indexOf("b"); // 1
list.join(" - "); // "a - b"Loops
Loops repeat code.
for
js
for (let i = 0; i < 5; i++) {
console.log("Count:", i); // 0, 1, 2, 3, 4
}The three parts are: start (let i = 0), condition (i < 5), and step (i++).
for...of
The easiest way to visit every item in an array:
js
for (const fruit of fruits) {
console.log(fruit);
}while
Repeats as long as a condition is true:
js
let lives = 3;
while (lives > 0) {
console.log("Lives left:", lives);
lives--;
}Array methods: map, filter, reduce
These methods take a callback function and are the modern way to work with lists.
js
const prices = [12, 5, 30, 8];
// map: transform each item → new array of the same length
const withTax = prices.map((p) => p * 1.2); // [14.4, 6, 36, 9.6]
// filter: keep items that pass a test
const cheap = prices.filter((p) => p < 10); // [5, 8]
// reduce: combine all items into one value
const total = prices.reduce((sum, p) => sum + p, 0); // 55
// find: first item that passes a test
const firstBig = prices.find((p) => p > 20); // 30
// forEach: do something with each item (returns nothing)
prices.forEach((p, index) => console.log(index, p));
// sort numbers (give a compare function!)
const sorted = [...prices].sort((a, b) => a - b); // [5, 8, 12, 30]Try it: a dynamic list
<input id="item" placeholder="Add a topic to learn">
<button id="add">Add</button>
<ul id="list"></ul>
<p id="stats"></p>Edit this example in the Playground.
Summary
- Arrays hold ordered lists; indexes start at 0.
- Use
push,pop,includes, and friends to work with arrays. - Loop with
for,for...of, orwhile. map,filter,reduce, andfindtransform data cleanly.
Saved in this browser.