Learning Goals
3 minBy the end of this lesson you will be able to:
- Create an array and read any item by its index.
- Explain why the last index is
length - 1. - Add and remove items with
.push()and.pop(). - Loop over every item with
for…ofand total them up.
Warm-Up · Too Many Variables
5 minLast lesson you wrote functions to avoid repeating a calculation. Here is repetition of a different kind.
const dish1 = 'nasi lemak';
const dish2 = 'roti canai';
const dish3 = 'char kway teow';
const dish4 = 'mee goreng';
console.log(dish1, dish2, dish3, dish4);Predict together
- The stall adds a fifth dish. What must change?
- How would you print all the dishes with a loop from Lesson 7?
Reveal
You would need a new variable and a new entry in the console.log. Worse, a loop cannot help at all — there is no way to say “the ith dish” when each has its own name. Today's fix is to keep them in one list.
New Concept · One Name, Many Values
12 minThink of a row of numbered lockers at a swimming pool. One row, one name, and each locker holds something different. You find yours by its number.
Making an array
const dishes = ['nasi lemak', 'roti canai', 'char kway teow'];
console.log(dishes);
console.log(dishes.length);[ 'nasi lemak', 'roti canai', 'char kway teow' ]
3Square brackets, values separated by commas. .length counts them — the same property you used on strings in Lesson 3.
Reaching one item
Indexes start at zero, exactly like string characters.
console.log(dishes[0]); // first
console.log(dishes[dishes.length - 1]); // last
console.log(dishes[7]); // nothing therenasi lemak
char kway teow
undefinedAsking for an index that does not exist is not an error — you get undefined. That silence is a common source of confusion, so check your lengths.
Growing and shrinking
const order = ['teh tarik'];
order.push('roti canai'); // add to the end
order.push('kaya toast');
console.log(order);
const removed = order.pop(); // take the last one off
console.log(removed, '→', order);[ 'teh tarik', 'roti canai', 'kaya toast' ]
kaya toast → [ 'teh tarik', 'roti canai' ]Notice order is a const, yet the list changed. const stops you pointing the name at a different array — it does not freeze the contents. Nearly every array in real code is a const.
Looping over a list
The for loop from Lesson 7 works with an index. But there is a cleaner form when you want every item:
for with an index
for (let i = 0; i < dishes.length; i++) {
console.log(i, dishes[i]);
}Use when you need the position number.
for…of
for (const dish of dishes) {
console.log(dish);
}Use when you only need the item. Shorter, and no off-by-one risk.
Arrays of numbers
const prices = [5.5, 1.5, 8.0];
let total = 0;
for (const price of prices) {
total = total + price;
}
console.log(`Total: RM ${total.toFixed(2)}`);Total: RM 15.00Why it matters
Every list you have ever scrolled — search results, a food-delivery menu, a chat history — is an array behind the scenes. In React you will turn an array straight into rows on the page, which is exactly what Lesson 10 sets up.
Worked Example · The Order Pad
12 minBuild a small order pad in pad.js.
Step 1 — Two matching lists
// pad.js — Warung Aisyah order pad
const items = ['nasi lemak', 'teh tarik', 'kuih'];
const prices = [5.5, 2.5, 1.5];
console.log(`${items.length} items on the pad`);3 items on the padPosition 0 in each list belongs together. Keeping two parallel arrays in step is fiddly — Lesson 11 shows a better way with objects. For now it works nicely.
Step 2 — Print the pad
Here you need the index, so use the counting for:
for (let i = 0; i < items.length; i++) {
console.log(`${i + 1}. ${items[i]} — RM ${prices[i].toFixed(2)}`);
}1. nasi lemak — RM 5.50
2. teh tarik — RM 2.50
3. kuih — RM 1.50i + 1 is only for the human-facing number. The array itself still starts at 0.
Step 3 — Total it with a function
Reuse the idea from Lesson 8 — one job, one function, and it returns:
function sum(numbers) {
let total = 0;
for (const n of numbers) {
total = total + n;
}
return total;
}
console.log(`Total: RM ${sum(prices).toFixed(2)}`);Total: RM 9.50Step 4 — Add to the order
items.push('roti canai');
prices.push(1.5);
console.log(`Now ${items.length} items, total RM ${sum(prices).toFixed(2)}`);Now 4 items, total RM 11.00Both arrays must be pushed to, or they fall out of step and prices[3] would be undefined.
Step 5 — Find the priciest
Track a “best so far” as you walk the list:
let dearestIndex = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[dearestIndex]) {
dearestIndex = i;
}
}
console.log(`Priciest: ${items[dearestIndex]}`);Priciest: nasi lemakWhat changed? The loop starts at 1, not 0 — item 0 is already the current best, so comparing it with itself would be wasted work. This “keep the best so far” pattern appears everywhere in programming.
Try It Yourself
13 minWork in pad.js or a new arrays.js.
Task 1 — Your own menu
Replace the items and prices with five of your own. Print the numbered pad and the total, both using your existing loop and
sum().Task 2 — Cheapest and average
Adapt the “priciest” loop to find the cheapest item instead. Then print the average price, rounded to two decimals.
const average = sum(prices) / prices.length;Task 3 — A running order
Start with an empty array,
const order = [];. Push three items onto it, print the list, then.pop()one off because the customer changed their mind. Print the list again.Finally, use
.includes()to check whether'teh tarik'is still in the order, and printtrueorfalse.
🔥 Mini-Challenge · The Missing Last Item
8 minYi Xuan's stock list skips a drink and shows an odd total. Find two mistakes.
// yixuan-stock.js — buggy
const drinks = ['kopi-O', 'teh tarik', 'milo ais', 'cendol'];
const stock = [12, 8, 5, 3];
for (let i = 0; i < drinks.length - 1; i++) {
console.log(drinks[i] + ': ' + stock[i]);
}
let totalStock = 0;
for (let i = 1; i <= stock.length; i++) {
totalStock = totalStock + stock[i];
}
console.log('Total stock: ' + totalStock);It works if: all four drinks are listed and the total stock prints as 28.
Reveal the answer
Mistake 1 — the list loop stops one item early.
i < drinks.length - 1 runs for indexes 0, 1, 2 — so cendol never prints. The - 1 belongs when you read the last index, not when you set a loop's limit. With <, use .length on its own.
Mistake 2 — the total loop runs off the end.
Starting at 1 skips the first value, and i <= stock.length reaches index 4, which does not exist. Adding undefined gives NaN:
Total stock: NaN// yixuan-stock.js — fixed
const drinks = ['kopi-O', 'teh tarik', 'milo ais', 'cendol'];
const stock = [12, 8, 5, 3];
for (let i = 0; i < drinks.length; i++) {
console.log(`${drinks[i]}: ${stock[i]}`);
}
let totalStock = 0;
for (const n of stock) { // for…of can't run off the end
totalStock = totalStock + n;
}
console.log(`Total stock: ${totalStock}`);kopi-O: 12
teh tarik: 8
milo ais: 5
cendol: 3
Total stock: 28Both bugs are off-by-one errors at opposite ends. Using for…of when you do not need the index removes that whole class of mistake.
Recap
3 min- An array is an ordered list written in square brackets.
- Indexes start at 0, so the last is
length - 1. - An index that does not exist gives
undefined, not an error. .push()adds to the end;.pop()removes from the end and returns it.conststops reassignment, but the contents can still change.for…ofwhen you need the items; countingforwhen you need the index.- Parallel arrays must be kept in step — objects (Lesson 11) do this better.
New words
- Array — an ordered list of values under one name.
- Element — one item in an array.
- Index — an item's position, counting from 0.
- for…of — a loop that visits each element in turn.
📦 Homework
4 min to brief · ~20 min to doRequired
- Write
marks.jsholding an array of eight test marks. Print every mark on its own numbered line, then the highest, the lowest and the average. - Use a
for…ofloop at least once and a countingforat least once. Bring the file next lesson.
Optional stretch
- Look up
.shift()and.unshift(). Write one sentence on how they differ from.pop()and.push(). - Try
drinks.join(', ')anddrinks.sort()in the console. What doessortdo to an array of numbers? The answer is surprising.