Arrays and loops
Keep lists of values in JavaScript arrays, read and change items by index, add and remove items, and repeat work with for...of, counting for loops and while loops.
🎯 By the end of this lesson you will be able to:
- Create arrays, read items by index and use length
- Add, remove and find items with push, pop, includes and indexOf
- Loop over arrays with for...of and count with a for loop
Outline
What you'll learn and why it matters
A shopping basket, a list of messages, a class register: real programs handle lists of things. An array holds many values in order, and a loop does the same job for each of them, whether there are 3 items or 3,000.
Creating and reading arrays
const drinks = ["Masala chai", "Filter coffee", "Lemon tea"];
console.log(drinks);
console.log(drinks.length);
console.log(drinks[0]);
console.log(drinks[2]);
console.log(drinks[drinks.length - 1]);Console (Chrome and Edge)
(3) ['Masala chai', 'Filter coffee', 'Lemon tea'] 3 Masala chai Lemon tea Lemon tea
Items are numbered from 0, so the first item is drinks[0] and the last is drinks[drinks.length - 1]. The console shows the array with its length in brackets, (3), followed by the items; click the small arrow beside it in Chrome to expand it.
| Index | 0 | 1 | 2 |
|---|---|---|---|
| Item | Masala chai | Filter coffee | Lemon tea |
Changing arrays
const basket = ["Samosa"];
basket.push("Banana bread");
basket.push("Masala chai");
console.log(basket);
const removed = basket.pop();
console.log(removed);
basket[0] = "Veg puff";
console.log(basket);
console.log(basket.includes("Banana bread"));
console.log(basket.indexOf("Banana bread"));
console.log(basket.join(" + "));Console (Chrome and Edge)
(3) ['Samosa', 'Banana bread', 'Masala chai'] Masala chai (2) ['Veg puff', 'Banana bread'] true 1 Veg puff + Banana bread
| Method | Does |
|---|---|
push(item) | Adds an item to the end |
pop() | Removes the last item and gives it back |
includes(item) | true if the item is in the array |
indexOf(item) | The item's position, or -1 if it is not there |
join(separator) | One string made of all items, with the separator between them |
splice(index, 1) | Removes 1 item at a position (used in the final project) |
Looping with for...of
for (const item of array) runs the block once for every item, in order:
const prices = [40, 50, 60, 25];
let total = 0;
for (const price of prices) {
total += price;
console.log(`Added ${price}, total ${total}`);
}
console.log(`Grand total: ${total}`);Console (Chrome and Edge)
Added 40, total 40 Added 50, total 90 Added 60, total 150 Added 25, total 175 Grand total: 175
This is the accumulator pattern: start a total before the loop, add to it inside, and use it after.
Counting loops
The classic for loop has three parts in its brackets: where to start, when to keep going, and what to do after each round.
for (let i = 1; i <= 5; i++) {
console.log(`7 x ${i} = ${7 * i}`);
}Console (Chrome and Edge)
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
| Part | Here | Means |
|---|---|---|
| Start | let i = 1 | Create a counter starting at 1 |
| Condition | i <= 5 | Keep looping while this is true |
| Step | i++ | Add 1 after each round |
Use a counting loop when you need the position too, for example to number a list:
const drinks = ["Masala chai", "Filter coffee", "Lemon tea"];
for (let i = 0; i < drinks.length; i++) {
console.log(`${i + 1}. ${drinks[i]}`);
}Console (Chrome and Edge)
1. Masala chai 2. Filter coffee 3. Lemon tea
while loops
A while loop repeats as long as its condition is true. Use it when you do not know in advance how many rounds you need:
let savings = 1000;
let months = 0;
while (savings < 2000) {
savings += 300;
months++;
}
console.log(`${months} months, savings ${savings}`);Console (Chrome and Edge)
4 months, savings 2200
Practice
Guided exercise
Count the passes
Given const marks = [78, 35, 91, 40, 22];, print each mark with pass (40 or more) or fail, then print how many passed.
- Create
let passed = 0;before the loop. - Loop with
for (const mark of marks). - Inside, use
ifto print the right word and add 1 topassedfor a pass. - After the loop, print the count.
Show the solution
const marks = [78, 35, 91, 40, 22];
let passed = 0;
for (const mark of marks) {
if (mark >= 40) {
console.log(`${mark}: pass`);
passed++;
} else {
console.log(`${mark}: fail`);
}
}
console.log(`${passed} of ${marks.length} passed`);Console (Chrome and Edge)
78: pass 35: fail 91: pass 40: pass 22: fail 3 of 5 passed
How to get there: The counter starts at 0 before the loop and only goes up for passes. 40 counts as a pass because the test is >=, not >.
Your turn
Longest word
Given const words = ["sun", "elephant", "tea", "giraffe"];, use a loop to find and print the longest word.
Show the solution
const words = ["sun", "elephant", "tea", "giraffe"];
let longest = "";
for (const word of words) {
if (word.length > longest.length) {
longest = word;
}
}
console.log(longest);Console (Chrome and Edge)
elephant
How to get there: Keep the best answer so far in a variable, and replace it whenever you find a longer word. Starting with an empty string means the first word always wins the first comparison.
Common mistakes
Using drinks[3] for the third item
You see: You get the fourth item or undefined
Fix: Indexes start at 0: the third item is drinks[2].
Writing i <= drinks.length in a counting loop
You see: The last round prints undefined
Fix: Use i < drinks.length.
Setting the total inside the loop
You see: The total only shows the last value
Fix: Create the accumulator before the loop.
A while loop whose condition never becomes false
You see: The tab freezes
Fix: Make sure each round moves towards the end.
Recap
- Arrays hold ordered lists; items are numbered from 0 and
lengthcounts them. - push, pop, includes, indexOf and join cover most everyday array jobs.
for (const item of array)visits every item; the accumulator pattern builds totals.- Counting
forloops give you a position;whileloops repeat until a condition changes.
Key terms
- Array
- An ordered list of values in one variable.
- Index
- An item's position in an array, starting at 0.
- Loop
- Code that repeats a block several times.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. With `const a = ["x", "y", "z"]`, what is `a[1]`?
2. What does `[3, 6, 9].indexOf(10)` give?
3. How many times does this loop run? for (let i = 0; i < 4; i++) { }
4. Why can you push to an array declared with const?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.