Run the same lines for every item of a list with for...of, count through its indexes with for and i++, and repeat while a condition holds with while. See why i < tasks.length stops in time where <= does not, why the counter is let, and make TaskKit add several tasks in one command and print them as a numbered list.
TypeScript
Fundamentals
`for`, `for...of`, and `while`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In the last lesson you read a list one line per item: tasks[0],
then tasks[1], then tasks[2]. That is fine for three. For thirty it
is thirty lines, and the day a thirty-first task arrives, the code
has to change again. The program knows how long the list is. It
should be able to go through it by itself.
Think of a teacher reading the class list aloud, name by name.
There is one instruction,
"read the name, wait for an answer", and the teacher does it for
every name on the sheet, top to bottom, and stops when the sheet
ends. Nobody writes the instruction out thirty times. By the end of
this lesson you can write a few lines once and have them run for
every item in a list, count as they go, or keep going for as long
as something is true. TaskKit takes several tasks in one command
and prints them as a numbered list.
The same lines for every item: for...of
A loop is a block of lines that runs again and again. Each run
of the block is one turn of the loop; you will also see the
word iteration, which means the same. The loop you will write
most often goes through a list one item at a time:
ts
for (const task of tasks) { console.log(task);}
Read the first line out loud: "for each task of tasks". The block
between the braces is the loop's body, the lines it repeats,
just as the braces of an if held the lines it controlled. On the
first turn the box task holds the first item of tasks, on the
second turn the second item, and so on. When no items are left,
the loop ends and the program carries on with the line after the
closing brace.
The player below runs a loop over three tasks. Press Next step
to walk it turn by turn, or press Play and watch:
CodeThe program, line by line. The marked line is the one the computer is running now; the lines above it have run.ts
Line 9.tasks = ["buy milk", "call mom", "pay rent"].
No items are left, so the loop ends and the line after it runs.
task belonged to the loop and is gone.
Prints Done
The loop's lines run once for every item, then it ends
The list is written one item per line here only so that it fits
beside the boxes. Both ways of writing it make the same list.
Three things in that walk are worth saying out loud:
The loop does not care how long the list is. Push a fourth
task and it takes four turns, with no change to the loop.
task is a new box on every turn. The player shows it in
the same place, but each turn makes it afresh and nothing ever
changes it, which is why const is right for it. Name it as one
item of the list: task of tasks, minute of minutes.
task exists only inside the loop. It is made in the loop's
first line and belongs to the loop, so, like a box made inside an
if's braces in Module 3, it is gone after the closing brace.
Now run one yourself. Press Step to follow it line by line, or
Run to see what it prints:
todo.tsts
const tasks = ["buy milk", "call mom", "pay rent"];for (const task of tasks) { console.log(`[ ] ${task}`);}console.log(`${tasks.length} things to do`);
It prints [ ] buy milk, [ ] call mom and [ ] pay rent, one
per turn, and then 3 things to do, once, because that line is
after the loop's closing brace.
Counting the turns: for
for...of hands you every item, but it never tells you which
number the item is. Sometimes the number is the point: a numbered
list, 1. buy milk, or a walk that starts somewhere other than
the first item. For that there is the counting form of for. It
keeps a counter, a let box that holds a number, 0 on the
first turn, 1 on the next, and you read the item with that number
as its index.
Its first line has three parts, separated by semicolons. This one
reads "start i at 0; keep going while i is less than the
length; add 1 to i after every turn":
ts
for (let i = 0; i < tasks.length; i++) {
Each part runs at its own moment:
let i = 0
Runs once, before the first turn: the counter starts at 0.
i < tasks.length
Asked before every turn. False, and the loop ends.
i++
Runs after every turn: 1 is added to the counter.
for (let i = 0; i < tasks.length; i++), part by part
The body runs between the second part and the third: after the
condition says true, before i++.
Two pieces are new. i++ adds 1 to the box i. It means the same
as i += 1, which Module 2 showed you as the short form of
i = i + 1; in a counting loop everybody writes i++. And i
itself is a name of one letter, where Module 2 asked for names that
read on their own. The counter of a loop is the one exception
programmers agree on: i is usually read as short for index.
It prints 1. buy milk, 2. call mom and 3. pay rent. People
count from 1, so the line prints i + 1, while tasks[i] reads
the item at index i, counted from 0. When i reaches 3, the
condition 3 < 3 is false, and the loop ends before it reads
tasks[3].
That condition is the whole safety of a counting loop. Last lesson's
common mistake was reading one past the end, and in a loop it hides
in a single character.
Bad — <= lets i reach the
length, one turn too many.
ts
const tasks = ["buy milk", "call mom", "pay rent"];for (let i = 0; i <= tasks.length; i++) { console.log(tasks[i].toUpperCase());}
Good — < stops at the last
index, 2.
ts
const tasks = ["buy milk", "call mom", "pay rent"];for (let i = 0; i < tasks.length; i++) { console.log(tasks[i].toUpperCase());}
The first prints all three tasks in capitals, then takes a fourth
turn with i at 3 and stops with TypeError: Cannot read properties of undefined (reading 'toUpperCase'). tsc (the
TypeScript compiler, which npx starts) stays quiet about it,
because square brackets assume the item is there. With a list, the
condition is always i < tasks.length.
Repeating while something is true: while
Both loops so far know their number of turns before they start: one
per item. Sometimes you cannot know it. You have an hour, and your
tasks take 25, 15, 30 and 10 minutes. How many of them, in order,
fit in the hour? That depends on the numbers, so you keep taking
the next task for as long as it still fits.
A while loop is made for that. It has only a condition:
before every turn it asks it, runs the body if it is true, and
ends the first time it is false. Press Step to watch the hour
fill up:
hour.tsts
const minutes = [25, 15, 30, 10];let used = 0;let count = 0;while (count < minutes.length && used + minutes[count] <= 60) { used += minutes[count]; count++;}console.log(`${count} tasks fit in an hour, ${used} minutes`);
It prints 2 tasks fit in an hour, 40 minutes. Before a third
turn, the next task would take used to 70, so the condition is
false and the loop ends. The condition has two parts for a reason: as
Module 3 showed, && stops at a false left side, so once count
reaches the end of the list, minutes[count] is never read.
A while only stops when its condition becomes false, so something
in the body has to move it there. Here it is count++ and
used += ….
If it happens in your terminal, the program never gives your prompt
back. Stop it with the keys that left Node's prompt in Module 1,
pressed once: a running program stops at the first press, where
Node's prompt needed two:
⌃ Control+C
Ctrl+C
Ctrl+C
Which loop when
All three repeat a block. What differs is the question you ask
before you choose one:
for (const task of tasks) { console.log(task);}
for...of
Does: Every item, in order, one per turn
Never: Never tells you the item's number
for (let i = 0; i < 3; i++) { console.log(i + 1);}
for
Does: Counts the turns in i, the item's number
Never: Never stops until its check is false
while (used < 60) { used += 25;}
while
Does: Repeats while a condition is true
Never: Never knows in advance how many turns
Every item, its number, or a condition: one loop each
Start with for...of: it cannot run past the end, and it has no
counter to get wrong. Switch to for when you need the number, or
a start other than the first item. Use while when the end depends
on something other than the list's length.
TaskKit takes several tasks
Now TaskKit's step for this lesson. So far add reads one task,
from process.argv.at(3) (argv, short for argument vector,
the list of words you typed). With a loop it can take as many as you
type: node index.ts add "buy milk" "call mom" "pay rent". The
tasks come after add, from index 3 of process.argv, so this is a job
for the counting for, starting at 3 instead of 0.
Open index.ts in ~/projects/taskkit and delete the line that
reads one task: the loop now reads each task itself.
case "add": for (let i = 3; i < process.argv.length; i++) { const tidyTask = process.argv[i].trim(); const newTask = tidyTask.slice(0, 1).toUpperCase() + tidyTask.slice(1); if (tidyTask === "") { console.log("Skipped an empty task"); } else if (tasks.length < limit) { console.log("Added:", newTask); tasks.push(newTask); } else { console.log("No room for:", newTask); } } if (tasks.length === 0) { console.log( `Add what? Try: node index.ts add "buy milk"` ); } break;
Each turn tidies one word and decides what to do with it. An empty
one is skipped, a task is added while there is room, and once the
list holds limit tasks, the rest are refused by name. Without
that condition, six tasks would make TaskKit print room for -1 more.
If no task was added at all, the hint from Module 3 still appears.
Notice process.argv[i] with square brackets. Module 3 swapped them
for .at(3), because square brackets are typed string even when
no word was typed, and .at() admits undefined.
Here the condition i < process.argv.length lets the body run only for
words that are there, so brackets are safe.
At the very end of the file, print the list one numbered line per
task instead of in Node's square brackets:
index.tsts
console.log("Your list:", tasks);console.log("Your list:");for (let i = 0; i < tasks.length; i++) { console.log(`${i + 1}. ${tasks[i]}`);}
npx tsc prints nothing: the file passes. Then TaskKit prints:
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Buy milkAdded: Call momAdded: Pay rentTasks added: 3 of 5, room for 2 moreList 60% fullYour list:1. Buy milk2. Call mom3. Pay rent
Run node index.ts help and it ends with Your list: and nothing
under it: over an empty list the loop takes no turns.
Now give it more than it has room for, with an empty word in the
middle: node index.ts add a b " " c d e f. It prints Skipped an empty task for the space, adds five, answers No room for: F, and
reports Tasks added: 5 of 5, room for 0 more.
Predict before you run
This loop does not start where the others did. Follow the counter
and decide what comes out first.
Predict
What is the first line this program prints?
ts
const tasks = ["buy milk", "call mom", "pay rent"];for (let i = 1; i < tasks.length; i++) { console.log(`${i}. ${tasks[i]}`);}
The common mistake: const in a counting loop
This course has told you to start every box with const, and
for (const task of tasks) works. So it is natural to write the
counter the same way.
Common mistake
Making the counter of a for with const
You want a numbered list, and you write the counter as you write
every other box:
Run the broken file with Node anyway: it prints 1. buy milk,
then stops at i++ with TypeError: Assignment to constant variable. When TS2588 points at a loop's i++, the counter
wants let.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each exercise is checked in your browser. Press Check when you
think you have it; if you are stuck, the hints come one at a time.
Exercise · Read the code
Read the last number a loop prints
What is the last line this loop prints?
ts
const tasks = ["buy milk", "call mom", "pay rent"];for (let i = 0; i < tasks.length; i++) { console.log(i);}
Exercise · Fix the error
Let the counter count
TypeScript refuses this loop. Fix it so it prints
Task 1: 15 min, Task 2: 30 min and Task 3: 5 min.
Loading the editor…
Exercise · Write the code
Add up the minutes
Your tasks take 15, 30 and 5 minutes. Use a for...of loop to add
every number in minutes to total, then print total. The
program prints 50.
Loading the editor…
Exercise · Predict the result
How many turns until the work is done
Ten minutes of work are left, and each turn of the loop does four.
What does the last line print?
ts
let left = 10;let turns = 0;while (left > 0) { left -= 4; turns++;}console.log(turns);
Recap
Recap · 3 questions
Check yourself
for (const task of tasks): what is task on turn two?
Check yourself
When does a for ask its condition, i < tasks.length?
Check yourself
You add tasks until the hour is full. Which loop?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
for, for...of, and while
What things are
Word
What it means
Loop
A block of lines that runs again and again
Turn
One run of the loop's body; also called an iteration
Body
The lines between the loop's braces
Counter
A let box that counts the turns, usually i
Code
Write
To
for (const task of tasks) { … }
Run the body once per item
for (let i = 0; i < tasks.length; i++)
Count through every index
tasks[i]
Read the item of this turn
i++
Add 1 to i; the same as i += 1
total += minute;
Add to a box on every turn
while (used < 60) { … }
Repeat while the condition is true
Rules
Rule
What it means
Start with for...of
It cannot run past the end
i < tasks.length
Never <=: it takes one turn too many
let for the counter
i++ changes it; const is TS2588
const in for...of
Each turn makes a new box
Move towards false
A while must change what its condition reads
Stuck loop
Control+C stops it (Ctrl+C on Windows and Linux)
Where to go next
You can now run the same lines for every item of a list with
for...of, count through its indexes with for, and repeat while a
condition holds with while, and you know which to reach for
first. TaskKit takes several tasks in one command, refuses the ones
it has no room for, and prints a numbered list.
Next is map, filter, find, some, and every. Many loops
you write do one of a few jobs: make a new list from every item,
keep only some items, or look for one. There each job gets a method
of its own, and the loop disappears into one line.
Before you move on, change limit to 3, predict which tasks
node index.ts add a b c d e refuses, then run it and compare. Put
limit back to 5 afterwards.