The problem with repeating yourself
Programs often do the same thing for every item in a collection: greet each friend, print each fruit, add up each price. Without a loop, the only tool you have is to write the statement once per item. This lesson shows how that goes, so that the for loop in the next lesson solves a problem you have felt.
Greeting four friends
Take an array of friends and a message that should be printed for each of them. Reading elements by index, the program looks like this:
let friends = ["Andy", "Mircea", "David", "Mary"];
console.log("Hey, " + friends[0]);
console.log("Hey, " + friends[1]);
console.log("Hey, " + friends[2]);
console.log("Hey, " + friends[3]);
It prints Hey, Andy, Hey, Mircea, Hey, David and Hey, Mary, one per line. For four friends this is tolerable, but it has three weaknesses that get worse as the array grows.
- It scales badly. A hundred friends means a hundred nearly identical lines. A thousand means a thousand.
- It breaks when the data changes. If a fifth friend is added to the array, nothing prints for them until someone writes a fifth line. If a friend is removed, the last line reads an index that no longer exists.
- It invites mistakes. Copying and pasting a line a hundred times makes it easy to forget to change an index, or to change one in the wrong place.
What goes wrong when the array shrinks
The second weakness is concrete. Suppose the array has three friends, but the code still has four lines:
let friends = ["Andy", "Mircea", "David"];
console.log("Hey, " + friends[0]);
console.log("Hey, " + friends[1]);
console.log("Hey, " + friends[2]);
console.log("Hey, " + friends[3]);
The last line reads index 3, which doesn't exist, so the array gives back undefined and the program prints Hey, undefined. Nothing stops with an error. The code is wrong, and it still runs.
The idea behind a loop
In the four lines, the only thing that changes is the index: 0, 1, 2, 3. A for loop captures exactly that pattern. You write the statement once and let the loop run it for each element, so the number of lines in your program no longer depends on the number of items in the data. The loop also reads the array as it is when the program runs, which fixes the changing-data problem.
The next lesson shows the syntax. For now, the goal is to feel what the repetition costs.
The lesson's exercise
The starting code declares an array of four fruits:
const fruits: string[] = ["banana", "orange", "pear", "kiwi"];
The exercise is to print "I eat FRUIT" for each fruit, one line per fruit, using only console.log and no loop. It works step by step:
- Pick an element by its index. Arrays count from zero, so
fruits[0]is"banana"andfruits[3]is"kiwi". - Join it to the text. The
+operator joins strings, so"I eat " + fruits[0]gives"I eat banana". The space at the end of"I eat "is needed, since+adds nothing between the pieces. - Repeat for each index. One
console.logfor each of the indices0to3.
const fruits: string[] = ["banana", "orange", "pear", "kiwi"];
console.log("I eat " + fruits[0]);
console.log("I eat " + fruits[1]);
console.log("I eat " + fruits[2]);
console.log("I eat " + fruits[3]);
The output is:
I eat banana
I eat orange
I eat pear
I eat kiwi
Now picture the same task for a hundred fruits, or for an array whose size isn't known until the program runs. This version can't handle the second case at all, because the number of lines is fixed when you write the code.
Common mistakes in the repeated version
- Starting at index 1. The first element is
fruits[0]. Beginning atfruits[1]skips the banana. - Going one too far. With four fruits the last index is
3. Usingfruits[4]printsI eat undefined. - Forgetting the space.
"I eat" + fruits[0]printsI eatbanana. - Editing only some lines. If you change the message on three lines and forget the fourth, the output is inconsistent. A loop has one line, so there is one place to change.
Key takeaways
- Writing one statement per element repeats code, scales badly and breaks when the data changes.
- Reading past the end of an array gives
undefined, not an error. - A for loop runs one statement for every element, so the code stays the same size however long the array is.