ProgramGuru

Iterating Over Arrays

Understand Iterating Over Arrays

Use for...of to visit array element values, a counted for loop when you need indexes, and forEach for a callback-based traversal.

What you will learn: the purpose of iterating over arrays, the rules TypeScript checks, and what its JavaScript behavior looks like in a runnable example.

What you’ll learn

  • Explain how iterating over arrays works and where its type rules apply.
  • Predict the exact output of the iterating over arrays example.
  • Diagnose a common issue: Do not confuse for.

Build the mental model

Different loops communicate different intentions. for...of yields values, whereas for...in yields enumerable property names (normally index strings for basic arrays) and is generally not the preferred array traversal tool.

Key distinction: TypeScript checks the declared types during development; emitted JavaScript carries out the value-level operation at runtime. A type declaration alone never validates untrusted runtime input.

See the relationship

Read this illustration from the first labeled part to the last. Compare it with the example and identify which parts are type checks and which parts run in JavaScript.

Iterating Over Arrays: explained visuallyStart array → for...of values → Accumulate sumStart arrayfor...of valuesAccumulate sumFollow the values through the operation
Iterating Over Arrays: Start array → for...of values → Accumulate sum.

Run the complete TypeScript example

This self-contained example uses fixed values, so it runs without reading input or depending on an external service. Paste it into the TypeScript Playground or save it as main.ts.

TypeScript program

const values: number[] = [3, 5, 7];
let sum = 0;
for (const value of values) sum += value;
console.log(sum);
for (let i = 0; i < values.length; i++) {
  console.log(`${i}: ${values[i]}`);
}

Verified output

15
0: 3
1: 5
2: 7

Run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. For projects with a tsconfig.json, build using that configuration instead.

Trace every important step

The for...of loop adds 3+5+7 and prints 15. The indexed loop begins at i=0 and prints each element with its numerical index.

Check each step: identify the input values, follow the JavaScript operation in execution order, and match the final expression with the exact output shown. An annotation can reject invalid source before execution, but does not change the value printed.

Avoid these common mistakes

Do not confuse for...of and for...in. The former reads values; the latter enumerates keys and may include unexpected enumerable properties.

How to debug: reproduce the issue in a minimal example. For compiler errors, inspect the inferred and declared types; for a runtime surprise, log the actual values and follow their references or branches.

Practice and experiment

Replace values with four numbers. Print only elements at even indexes using a counted loop.

Practice routine: predict the result on paper, edit one part of the code, compile under --strict, run the JavaScript, and explain whether TypeScript caught an error or JavaScript simply behaved differently.

Check your understanding

Which loop directly yields array element values?
Choose one answer. You can try again.

Answer and explanation

for...of.

Use for...of to visit array element values, a counted for loop when you need indexes, and forEach for a callback-based traversal.

Review the key idea

Iterating Over Arrays: Use for...of to visit array element values, a counted for loop when you need indexes, and forEach for a callback-based traversal.

The for...of loop adds 3+5+7 and prints 15. The indexed loop begins at i=0 and prints each element with its numerical index.

Before continuing, explain one valid use case, one common pitfall, and the separation between compile-time checking and runtime behavior for this feature.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Array Methods →