TypeScript Tutorial
TypeScript For Loop
for packs init, condition, and step in one line. Use it when you know how many times to repeat.
Three parts in one line
A classic for loop has three slots separated by semicolons: initialize, condition, step. The initialize runs once. Then TypeScript checks the condition, runs the body, runs the step, and checks again, until the condition is false.
That is the same three jobs a while loop has, written where you can see them together. Usefor when the number of passes is known: 0 to n minus one, 1 to 10, every index in an array.
A complete for program
let i = 0 starts the counter. i < 5 is the test. i = i + 1 is the step. The body prints the current i. The values printed are 0, 1, 2, 3, 4 — five times, not six.
Example
for (let i: number = 0; i < 5; i = i + 1) {
console.log(i);
}Run this in /typescript/try. Counting from 0 is the usual habit because array indexes start at 0.
Read the header left to right
| Slot | This example | When it runs |
|---|---|---|
| Init | let i: number = 0 | Once, before the first check |
| Condition | i < 5 | Before every pass, including the first |
| Step | i = i + 1 | After each pass, before the next check |
i++ means the same as i = i + 1 here. You will see ++ in other people’s code. Either form is fine for a counter.
The variable declared in init exists only inside the loop. After the closing brace, i is gone.
Count the other way
Start high and subtract if you need a countdown. The condition still has to become false. Herei goes 5, 4, 3, 2, 1, then i >= 1 fails.
Example
for (let i: number = 5; i >= 1; i = i - 1) {
console.log(i);
}
console.log("done");for-of over a list
When you already have a collection and you want each value, TypeScript gives you for...of:for (const n of nums). No index. No length. The loop binds n to each element in turn. This is the analog of C++ range-for.
Example
const nums: number[] = [10, 20, 30];
for (const n of nums) {
console.log(n);
}
const word: string = "hi";
for (const ch of word) {
console.log(ch);
}for...of also walks the characters of a string. Arrays as a type come in a later chapter; this is enough to walk a short list.
Which loop to write
- Known count or indexes: classic
for. - Every element in an array, no index needed:
for...of. - Keep going until a condition changes (input, a flag):
while.
A for...of does not give you the index. If you need the position as well as the value, use a classic for with i. There is also for...in, which walks keys, not values. Do not use for...in on arrays in this course.
Off-by-one
i < n runs n times when i starts at 0. i <= n runs n + 1 times. Both are valid; they mean different things. For an array of length n, the last valid index is n minus one, so the test is i < n.
Next: break and continue — leaving a loop early, or skipping one pass.