> ## 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.

# JavaScript Generator Method

A generator method is a function defined within an object literal or a class that returns a `Generator` object. Denoted by an asterisk (`*`) preceding the method name, it allows the method to pause and resume its execution context using the `yield` keyword. Generator methods inherently conform to both the iterable and iterator protocols.

## Syntax Contexts

The asterisk (`*`) precedes the method name. JavaScript allows whitespace between the asterisk and the method identifier (e.g., `* generatorMethod() { ... }` is perfectly valid syntax). Generator methods can be declared in object literals, as class instance methods, and as class static methods.

**Object Literals:**

```javascript theme={"dark"}
const iterableObject = {
  * generatorMethod() { // Whitespace between asterisk and name is permitted
    yield 1;
    yield 2;
  }
};
```

**Classes (Instance and Static):**

```javascript theme={"dark"}
class Collection {
  // Instance generator method
  *traverse() {
    yield 'node1';
    yield 'node2';
  }

  // Static generator method
  static *generateDefaults() {
    yield 'defaultA';
    yield 'defaultB';
  }
}
```

**Computed Property Names:**
Generator methods fully support ES6 computed property names. The asterisk precedes the bracket notation.

```javascript theme={"dark"}
const dynamicName = 'customIterator';

const obj = {
  *[dynamicName]() {
    yield 'dynamic';
  }
};
```

## Execution Mechanics

1. **Initialization:** Invoking a generator method does not execute its body. Instead, it returns a suspended `Generator` instance.
2. **The `next()` Method:** Execution begins only when the `next()` method is called on the returned generator object. The method runs until it encounters a `yield` expression, which pauses the execution state.
3. **IteratorResult Object:** The `next()` method returns an `IteratorResult` object to the caller containing two properties:
   * `value`: The evaluated expression following the `yield` keyword.
   * `done`: A boolean indicating whether the generator has completed execution.
4. **Two-Way Communication:** The `next()` method can accept an optional argument. Inside the generator, the paused `yield` expression evaluates to the argument passed to the *subsequent* `next()` call that resumes execution. This allows the caller to inject values back into the generator's internal scope.

```javascript theme={"dark"}
const interactive = {
  *dialogue() {
    // The first next() call starts execution and yields 'Hello'
    const firstReply = yield 'Hello'; 
    
    // The second next('Hi!') resumes execution, assigning 'Hi!' to firstReply
    const secondReply = yield `You said: ${firstReply}`;
    
    // The third next('Bye') resumes execution, assigning 'Bye' to secondReply
    return `Finished with: ${secondReply}`;
  }
};

const gen = interactive.dialogue();

console.log(gen.next());        // { value: 'Hello', done: false }
console.log(gen.next('Hi!'));   // { value: 'You said: Hi!', done: false }
console.log(gen.next('Bye'));   // { value: 'Finished with: Bye', done: true }
```

## Delegation via `yield*`

Generator methods can delegate iteration control to another iterable object (such as an Array, Map, or another Generator) using the `yield*` expression.

```javascript theme={"dark"}
class Tree {
  *branch() {
    yield 'leaf1';
    yield 'leaf2';
  }

  *trunk() {
    yield 'root';
    yield* this.branch(); // Delegates to the branch generator method
    yield 'canopy';
  }
}

const myTree = new Tree();
const iterator = myTree.trunk();

console.log(iterator.next().value); // 'root'
console.log(iterator.next().value); // 'leaf1'
console.log(iterator.next().value); // 'leaf2'
console.log(iterator.next().value); // 'canopy'
```

## `this` Binding

Like standard methods, the `this` context inside a generator method refers to the object or class instance upon which the method was called. Arrow functions cannot be used as generator methods, so lexical `this` binding via arrow syntax is not applicable to the generator declaration itself.

```javascript theme={"dark"}
const counter = {
  base: 10,
  *countUp() {
    yield this.base + 1;
    yield this.base + 2;
  }
};

const gen = counter.countUp();
console.log(gen.next().value); // 11
```

<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 JavaScript 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>
