> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript For-of Loop

The `for...of` statement executes a loop that operates on a sequence of values sourced from an iterable object. It invokes the iterable protocol by calling the object's `[Symbol.iterator]()` method, retrieving the values yielded by the iterator and abstracting away the manual management of loop counters or `.next()` state evaluations.

## Syntax

```typescript theme={"dark"}
for (const variable of iterable) {
  // execution block
}
```

* **`variable`**: Receives the value yielded by the iterator on each step. It is typically declared with `const` or `let`. TypeScript automatically infers the type of this variable based on the generic type of the iterable.
* **`iterable`**: Any object that structurally satisfies the iterable protocol, meaning it possesses a property with a `Symbol.iterator` key that returns an iterator.

## Type Inference

TypeScript leverages the type signature of the iterable to enforce type safety within the loop block. If an array is typed as `number[]`, the loop variable is strictly inferred as `number`.

```typescript theme={"dark"}
const sequence: number[] = [10, 20, 30];

// TypeScript infers 'item' as 'number'
for (const item of sequence) {
    console.log(item.toExponential());
}
```

## Implementing the Iterable Protocol

To utilize a `for...of` loop on a custom TypeScript class or object, the entity must structurally satisfy the iterable protocol. Because TypeScript uses structural typing, an explicit `implements Iterable<T>` declaration is entirely optional. The object only needs to define a valid `[Symbol.iterator]()` method that returns an object conforming to the `Iterator<T>` interface, which in turn yields `IteratorResult<T>` objects.

```typescript theme={"dark"}
class DataStream {
    private buffer: string[] = ["chunk1", "chunk2", "chunk3"];

    // Structurally satisfies Iterable<string>
    [Symbol.iterator](): Iterator<string> {
        let cursor = 0;
        const data = this.buffer;

        return {
            next(): IteratorResult<string> {
                if (cursor < data.length) {
                    return { done: false, value: data[cursor++] };
                }
                return { done: true, value: undefined };
            }
        };
    }
}

const stream = new DataStream();

// 'chunk' is inferred as 'string' based on the iterator's return type
for (const chunk of stream) {
    console.log(chunk);
}
```

## Asynchronous Iteration

TypeScript supports the `for await...of` variant to consume objects implementing the `AsyncIterable<T>` protocol. This is used when the iterator's `next()` method returns a `Promise<IteratorResult<T>>`.

```typescript theme={"dark"}
async function consumeStream(stream: AsyncIterable<Uint8Array>): Promise<void> {
    for await (const chunk of stream) {
        // 'chunk' is inferred as 'Uint8Array'
        console.log(chunk.byteLength);
    }
}
```

## Compiler Configuration (`downlevelIteration`)

When the TypeScript compiler target (`compilerOptions.target`) is set to ES5 or ES3, native support for the iterable protocol does not exist. By default, TypeScript will only allow `for...of` loops on standard Arrays and string types in these environments.

To iterate over other iterables (like `Map`, `Set`, or custom iterable implementations) when targeting ES5/ES3, the `downlevelIteration` flag must be enabled in `tsconfig.json`.

```json theme={"dark"}
{
  "compilerOptions": {
    "target": "ES5",
    "downlevelIteration": true
  }
}
```

When enabled, the compiler injects helper functions (such as `__values`) into the emitted JavaScript to manually emulate the ES6 iteration protocol, ensuring runtime compatibility at the cost of slightly increased bundle size.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor TypeScript Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
