for...of Loop
Learn for...of Loop
A for...of loop visits values produced by an iterable such as an array, string, Map or Set.
In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.
What you’ll learn
- Explain the main rule behind for...of loop.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
The loop variable receives each element value in sequence. For arrays it is normally clearer than a numeric index when you only need values. TypeScript infers the element type from the iterable, helping catch invalid operations within the body.
Run a complete TypeScript example
Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.
TypeScript code
const fruits: string[] = ["Apple", "Mango", "Grape"];
for (const fruit of fruits) {
console.log(fruit.toUpperCase());
}Verified output
APPLE
MANGO
GRAPEHow to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.
Trace the execution
Each iteration binds fruit to one array element. toUpperCase creates and prints the corresponding uppercase string.
Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.
Common mistakes and how to avoid them
for...of yields values, not array indexes. Use entries() or a standard for loop if you need both index and value.
Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.
Practice it yourself
Add a fourth fruit. Then try for (const [index, fruit] of fruits.entries()) and print each position.
Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.
Check your understanding
Review the key idea
for...of Loop: The loop variable receives each element value in sequence.
for...of follows the iterable protocol to retrieve values.
Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.
Reaching the recap and completing the quizzes are separate milestones.