← Web basics: HTML, CSS and JavaScript
Arrays and loops
Keep many values in one list and go through them one by one.
An array is an ordered list of values in square brackets: ["rice", "beans", "corn"]. Each item has a position number called an index, starting at 0, so fruits[0] is the first item. .length tells you how many items there are, and .push(x) adds x to the end. To do something with every item, use a loop. The for...of loop is the friendliest: for (const item of list) { ... } runs the body once per item, with item holding each value in turn.
const prices = [3, 8, 2];
prices.push(5); // [3, 8, 2, 5]
prices[0]; // 3
prices.length; // 4
let total = 0;
for (const p of prices) {
total = total + p;
}
// total is 18The loop visits 3, then 8, then 2, then 5, adding each to total. Starting total at 0 before the loop is the usual pattern for adding things up.
There is also the classic counting loop: for (let i = 0; i < list.length; i++) { ... list[i] ... }. It is useful when you need the index number.
The last item is always at index length - 1. Asking for an index that does not exist gives undefined, not an error.