PUNGGOL TUITION · PRACTICAL MASTERY GUIDE
If a learner understands Array.flatMap but becomes confused when an iterator pipeline runs only as values are requested, the missing idea is evaluation order. Iterator.prototype.flatMap is a lazy one-to-many transformation with an active outer iterator and, at times, an active inner iterator.
The core lesson is immediate: for each outer value, the helper calls a mapper with value and zero-based outer index, requires an iterable object result, then yields that inner iterator’s values before advancing the outer source. Construction is lazy, flattening is one level, and cleanup matters when errors or early stopping occur.
This guide treats JavaScript Iterator.prototype.flatMap as a reasoning skill. It begins with the governing model, moves through worked examples and diagnostic routes, and ends with transfer cases, practice with explained answers, parent decisions and FAQs. The examples are proposed home or lesson activities; they are not claims about a physical Punggol branch, school affiliation, timetable, class size, fee or guaranteed result.
For a Punggol family, the practical aim is simple: a learner should be able to use a short study block before schoolwork, after CCA, or during a weekend library session without needing a large project. Each chapter is designed so the smallest useful example can be completed, discussed and saved as a test fixture.
The official technical reference for this article is TC39 Iterator Helpers specification for Iterator.prototype.flatMap. Where the feature is version-sensitive or still developing, the article states that boundary explicitly. Examples were independently checked against the runtime or specification named in the reference section.
Choose a reading route
If the immediate concern is “I can copy the syntax but I cannot explain the result”, use the first route. If a real project is already failing, use the diagnostic route. Parents can use the final route to decide whether more practice, a smaller prerequisite or a different example is needed. For the wider learning framework, see How Studying Works.
Start from the model: Chapters 1–4. Begin with A lazy one-to-many iterator helper and continue in order to Mapper arguments: value and zero-based index.
Diagnose a confusing result: Chapters 5–8. Begin with Mapped results must be iterable and continue in order to Generator objects are natural inner iterables.
Build reliable examples: Chapters 9–12. Begin with Output order is depth-first by outer item and continue in order to take() can bound an infinite expansion.
Transfer to real work: Chapters 13–16. Begin with Zero-output mapping filters while mapping and continue in order to Early consumer stop closes active work.
Decide and teach: Chapters 17–20. Begin with Infinite inner iterables can starve later outer values and continue in order to Choosing flatMap for the right pipeline.
Open the full 20-chapter index
- 1. A lazy one-to-many iterator helper
- 2. The receiver becomes an iterator record
- 3. The mapper must be callable
- 4. Mapper arguments: value and zero-based index
- 5. Mapped results must be iterable
- 6. Strings are primitive mapper results and are rejected
- 7. Arrays flatten one level
- 8. Generator objects are natural inner iterables
- 9. Output order is depth-first by outer item
- 10. Laziness can avoid unnecessary mapping
- 11. Partial consumption preserves the remaining iterator state
- 12. take() can bound an infinite expansion
- 13. Zero-output mapping filters while mapping
- 14. Mapper errors terminate the helper
- 15. Inner iterator errors propagate and trigger cleanup
- 16. Early consumer stop closes active work
- 17. Infinite inner iterables can starve later outer values
- 18. flatMap versus map
- 19. flatMap versus eager Array.flatMap
- 20. Choosing flatMap for the right pipeline
CHAPTER 1 OF 20 · Back to contents
1. A lazy one-to-many iterator helper
The short answer: Iterator.prototype.flatMap maps each outer value to an iterable and yields that iterable’s values lazily. The governing rule is: One outer value can produce zero, one or many output values, and no output is pulled until a consumer asks.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
The proposal defines flatMap as an Iterator Helper. It consumes the outer iterator step by step, calls the mapper, obtains an inner iterator from the mapped value, and yields inner values before requesting the next outer value. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the a lazy one-to-many iterator helper example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
const out = Iterator.from([1,2,3]).flatMap(n => [n, n*10]);
console.log(out.toArray());
Expected result and reasoning. The result is [1,10,2,20,3,30]. Each mapped array is flattened exactly once and kept in outer order. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Calling this “Array.flatMap for every object” hides iterator consumption and laziness. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “When does the outer iterator advance, and how many inner values are yielded for each item?”
- Evidence to collect: mapper calls and yielded sequence
- Variable to hold constant: the surrounding setup, so the comparison isolates a lazy one-to-many iterator helper.
- Variable to change: consume only the first two outputs
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For a lazy one-to-many iterator helper, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a small data pipeline. Apply a lazy one-to-many iterator helper in a small data pipeline. The central question is whether the same rule still governs after the context changes. Iterator.prototype.flatMap maps each outer value to an iterable and yields that iterable’s values lazily. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “One outer value can produce zero, one or many output values, and no output is pulled until a consumer asks.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a paginated result stream. Apply a lazy one-to-many iterator helper in a paginated result stream. The central question is whether the same rule still governs after the context changes. Iterator.prototype.flatMap maps each outer value to an iterable and yields that iterable’s values lazily. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “One outer value can produce zero, one or many output values, and no output is pulled until a consumer asks.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a browser console fixture. Apply a lazy one-to-many iterator helper in a browser console fixture. The central question is whether the same rule still governs after the context changes. Iterator.prototype.flatMap maps each outer value to an iterable and yields that iterable’s values lazily. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “One outer value can produce zero, one or many output values, and no output is pulled until a consumer asks.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a validation pipeline. Apply a lazy one-to-many iterator helper in a validation pipeline. The central question is whether the same rule still governs after the context changes. Iterator.prototype.flatMap maps each outer value to an iterable and yields that iterable’s values lazily. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “One outer value can produce zero, one or many output values, and no output is pulled until a consumer asks.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Predict the six outputs and mark which outer value produced each pair. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. The mapping is 1→[1,10], 2→[2,20], 3→[3,30], concatenated in order. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Require the learner to narrate outer and inner progress separately. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain a lazy one-to-many iterator helper, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Contents · Full contents · Next: The receiver becomes an iterator record →
CHAPTER 2 OF 20 · Back to contents
2. The receiver becomes an iterator record
The short answer: The method operates on an iterator-like receiver, including objects adapted with Iterator.from. The governing rule is: The helper begins by converting this to an object and obtaining a direct iterator record.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
Iterator helpers work at the iterator layer. Iterator.from is the clearest bridge from arrays and other iterables in examples. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the the receiver becomes an iterator record example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
const it = Iterator.from(new Set(['a','b']));
console.log(it.flatMap(x => [x,x]).toArray());
Expected result and reasoning. The output is [‘a’,’a’,’b’,’b’] in Set iteration order. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Assuming every iterable already exposes helper methods fails on runtimes or objects without the proposal’s iterator prototype integration. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Is the receiver an iterator helper-capable object in this runtime?”
- Evidence to collect: runtime version, receiver type and method presence
- Variable to hold constant: the surrounding setup, so the comparison isolates the receiver becomes an iterator record.
- Variable to change: remove Iterator.from and inspect the receiver
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For the receiver becomes an iterator record, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a generator exercise. Apply the receiver becomes an iterator record in a generator exercise. The central question is whether the same rule still governs after the context changes. The method operates on an iterator-like receiver, including objects adapted with Iterator.from. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The helper begins by converting this to an object and obtaining a direct iterator record.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: an infinite sequence. Apply the receiver becomes an iterator record in an infinite sequence. The central question is whether the same rule still governs after the context changes. The method operates on an iterator-like receiver, including objects adapted with Iterator.from. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The helper begins by converting this to an object and obtaining a direct iterator record.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a Node command-line script. Apply the receiver becomes an iterator record in a Node command-line script. The central question is whether the same rule still governs after the context changes. The method operates on an iterator-like receiver, including objects adapted with Iterator.from. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The helper begins by converting this to an object and obtaining a direct iterator record.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a nested collection. Apply the receiver becomes an iterator record in a nested collection. The central question is whether the same rule still governs after the context changes. The method operates on an iterator-like receiver, including objects adapted with Iterator.from. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The helper begins by converting this to an object and obtaining a direct iterator record.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Explain why Iterator.from is useful even when the source is already iterable. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. It normalises the source to an iterator object that exposes the helper API supported by the runtime. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Treat feature detection and runtime version as part of the example. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain the receiver becomes an iterator record, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: A lazy one-to-many iterator helper · Full contents · Next: The mapper must be callable →
CHAPTER 3 OF 20 · Back to contents
3. The mapper must be callable
The short answer: flatMap validates that its mapper argument is a function. The governing rule is: A non-callable mapper triggers a TypeError before useful iteration.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
The specification explicitly checks IsCallable(mapper). This is an API contract error, not an empty result. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the the mapper must be callable example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
try { Iterator.from([1]).flatMap(null).toArray(); }
catch (e) { console.log(e.name); }
Expected result and reasoning. The fixture prints TypeError. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Explaining the error as “null has no values” misses the earlier callable validation. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Did construction reject the mapper, or did iteration fail later?”
- Evidence to collect: error name and whether source advanced
- Variable to hold constant: the surrounding setup, so the comparison isolates the mapper must be callable.
- Variable to change: replace null with x => [x]
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For the mapper must be callable, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a paginated result stream. Apply the mapper must be callable in a paginated result stream. The central question is whether the same rule still governs after the context changes. flatMap validates that its mapper argument is a function. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “A non-callable mapper triggers a TypeError before useful iteration.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a browser console fixture. Apply the mapper must be callable in a browser console fixture. The central question is whether the same rule still governs after the context changes. flatMap validates that its mapper argument is a function. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “A non-callable mapper triggers a TypeError before useful iteration.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a validation pipeline. Apply the mapper must be callable in a validation pipeline. The central question is whether the same rule still governs after the context changes. flatMap validates that its mapper argument is a function. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “A non-callable mapper triggers a TypeError before useful iteration.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a small data pipeline. Apply the mapper must be callable in a small data pipeline. The central question is whether the same rule still governs after the context changes. flatMap validates that its mapper argument is a function. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “A non-callable mapper triggers a TypeError before useful iteration.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Predict whether any source value is consumed before the error. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. The mapper validation fails before normal iteration begins, so the example should not rely on a source value being pulled. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Ask learners to distinguish argument validation from mapper-result validation. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain the mapper must be callable, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: The receiver becomes an iterator record · Full contents · Next: Mapper arguments: value and zero-based index →
CHAPTER 4 OF 20 · Back to contents
4. Mapper arguments: value and zero-based index
The short answer: The mapper receives the current outer value and a counter that starts at zero. The governing rule is: The index counts outer values processed, not flattened outputs produced.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
The counter increments once for each outer next value passed to the mapper, regardless of the length of the returned iterable. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the mapper arguments: value and zero-based index example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
const out=Iterator.from(['a','b']).flatMap((v,i)=>[i,v]);
console.log(out.toArray());
Expected result and reasoning. The output is [0,’a’,1,’b’]. Indices correspond to two outer mapper calls. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Counting inner yields would make the second index 2, which is not the defined behaviour. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Am I counting mapper calls or output values?”
- Evidence to collect: mapper log with value and index
- Variable to hold constant: the surrounding setup, so the comparison isolates mapper arguments: value and zero-based index.
- Variable to change: return three inner values for the first item
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For mapper arguments: value and zero-based index, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: an infinite sequence. Apply mapper arguments: value and zero-based index in an infinite sequence. The central question is whether the same rule still governs after the context changes. The mapper receives the current outer value and a counter that starts at zero. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The index counts outer values processed, not flattened outputs produced.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a Node command-line script. Apply mapper arguments: value and zero-based index in a Node command-line script. The central question is whether the same rule still governs after the context changes. The mapper receives the current outer value and a counter that starts at zero. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The index counts outer values processed, not flattened outputs produced.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a nested collection. Apply mapper arguments: value and zero-based index in a nested collection. The central question is whether the same rule still governs after the context changes. The mapper receives the current outer value and a counter that starts at zero. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The index counts outer values processed, not flattened outputs produced.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a generator exercise. Apply mapper arguments: value and zero-based index in a generator exercise. The central question is whether the same rule still governs after the context changes. The mapper receives the current outer value and a counter that starts at zero. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The index counts outer values processed, not flattened outputs produced.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Return [v,v,v] from the first call and predict the second call’s index. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. The second outer call still receives index 1 because the counter tracks outer values only. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Use a deliberately uneven inner length to expose the misconception. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain mapper arguments: value and zero-based index, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: The mapper must be callable · Full contents · Next: Mapped results must be iterable →
CHAPTER 5 OF 20 · Back to contents
5. Mapped results must be iterable
The short answer: Each mapper result is converted to an iterator that flatMap can consume. The governing rule is: Returning a non-iterable object cannot supply inner values and causes a TypeError.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
The helper obtains an iterator from each mapped result. Arrays, Sets and generator objects work; plain objects without an iterator do not. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the mapped results must be iterable example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
try {
Iterator.from([1]).flatMap(n => ({n})).toArray();
} catch(e) { console.log(e.name); }
Expected result and reasoning. The output is TypeError because {n:1} is not iterable. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Expecting object properties to be flattened confuses iteration with enumeration. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Does the mapped value implement the iterable protocol needed for inner iteration?”
- Evidence to collect: typeof value, Symbol.iterator presence and error
- Variable to hold constant: the surrounding setup, so the comparison isolates mapped results must be iterable.
- Variable to change: return [n] instead of {n}
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For mapped results must be iterable, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a browser console fixture. Apply mapped results must be iterable in a browser console fixture. The central question is whether the same rule still governs after the context changes. Each mapper result is converted to an iterator that flatMap can consume. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Returning a non-iterable object cannot supply inner values and causes a TypeError.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a validation pipeline. Apply mapped results must be iterable in a validation pipeline. The central question is whether the same rule still governs after the context changes. Each mapper result is converted to an iterator that flatMap can consume. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Returning a non-iterable object cannot supply inner values and causes a TypeError.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a small data pipeline. Apply mapped results must be iterable in a small data pipeline. The central question is whether the same rule still governs after the context changes. Each mapper result is converted to an iterator that flatMap can consume. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Returning a non-iterable object cannot supply inner values and causes a TypeError.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a paginated result stream. Apply mapped results must be iterable in a paginated result stream. The central question is whether the same rule still governs after the context changes. Each mapper result is converted to an iterator that flatMap can consume. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Returning a non-iterable object cannot supply inner values and causes a TypeError.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Compare a plain object, an array and a Set as mapper results. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. The array and Set are iterable; the plain object is not unless it defines an iterator. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Ask for protocol evidence instead of category labels like “collection”. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain mapped results must be iterable, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Mapper arguments: value and zero-based index · Full contents · Next: Strings are primitive mapper results and are rejected →
CHAPTER 6 OF 20 · Back to contents
6. Strings are primitive mapper results and are rejected
The short answer: The current Iterator Helpers specification rejects primitive mapper results, even iterable strings. The governing rule is: GetIteratorFlattenable is used with reject-primitives, so a primitive string is not accepted here.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
This is a subtle difference from casually saying “anything iterable works.” The specification’s flatMap algorithm explicitly requests primitive rejection. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the strings are primitive mapper results and are rejected example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
try { Iterator.from(['ab']).flatMap(x => x).toArray(); }
catch(e) { console.log(e.name); }
Expected result and reasoning. The verified modern runtime prints TypeError for the primitive string mapper result. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Assuming string iteration automatically makes this case valid ignores the reject-primitives mode. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Is the mapper result an object iterable or a primitive iterable?”
- Evidence to collect: typeof mapped result and exact error
- Variable to hold constant: the surrounding setup, so the comparison isolates strings are primitive mapper results and are rejected.
- Variable to change: return […x] instead of x
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For strings are primitive mapper results and are rejected, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a Node command-line script. Apply strings are primitive mapper results and are rejected in a Node command-line script. The central question is whether the same rule still governs after the context changes. The current Iterator Helpers specification rejects primitive mapper results, even iterable strings. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “GetIteratorFlattenable is used with reject-primitives, so a primitive string is not accepted here.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a nested collection. Apply strings are primitive mapper results and are rejected in a nested collection. The central question is whether the same rule still governs after the context changes. The current Iterator Helpers specification rejects primitive mapper results, even iterable strings. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “GetIteratorFlattenable is used with reject-primitives, so a primitive string is not accepted here.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a generator exercise. Apply strings are primitive mapper results and are rejected in a generator exercise. The central question is whether the same rule still governs after the context changes. The current Iterator Helpers specification rejects primitive mapper results, even iterable strings. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “GetIteratorFlattenable is used with reject-primitives, so a primitive string is not accepted here.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: an infinite sequence. Apply strings are primitive mapper results and are rejected in an infinite sequence. The central question is whether the same rule still governs after the context changes. The current Iterator Helpers specification rejects primitive mapper results, even iterable strings. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “GetIteratorFlattenable is used with reject-primitives, so a primitive string is not accepted here.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Make the smallest change that lets ‘ab’ yield ‘a’,’b’. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. Return an array such as […x]; it is an iterable object and therefore supplies the two inner values. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
This is a good check that the learner consulted the exact helper contract rather than a slogan. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain strings are primitive mapper results and are rejected, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Mapped results must be iterable · Full contents · Next: Arrays flatten one level →
CHAPTER 7 OF 20 · Back to contents
7. Arrays flatten one level
The short answer: An array returned by the mapper supplies its elements as inner values. The governing rule is: flatMap flattens the mapper’s returned iterable one level; it does not recursively flatten nested arrays.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
The helper iterates the returned array. If one array element is itself an array, that nested array is yielded as a value. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the arrays flatten one level example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
const out=Iterator.from([1]).flatMap(n => [[n,n+1],[n+2]]);
console.log(out.toArray());
Expected result and reasoning. The result contains two arrays: [[1,2],[3]]. It does not become [1,2,3]. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Importing the meaning of recursive flattening produces the wrong shape. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “What are the direct elements of the mapped iterable?”
- Evidence to collect: output types and nesting depth
- Variable to hold constant: the surrounding setup, so the comparison isolates arrays flatten one level.
- Variable to change: add another flatMap stage for nested arrays
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For arrays flatten one level, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a validation pipeline. Apply arrays flatten one level in a validation pipeline. The central question is whether the same rule still governs after the context changes. An array returned by the mapper supplies its elements as inner values. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “flatMap flattens the mapper’s returned iterable one level; it does not recursively flatten nested arrays.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a small data pipeline. Apply arrays flatten one level in a small data pipeline. The central question is whether the same rule still governs after the context changes. An array returned by the mapper supplies its elements as inner values. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “flatMap flattens the mapper’s returned iterable one level; it does not recursively flatten nested arrays.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a paginated result stream. Apply arrays flatten one level in a paginated result stream. The central question is whether the same rule still governs after the context changes. An array returned by the mapper supplies its elements as inner values. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “flatMap flattens the mapper’s returned iterable one level; it does not recursively flatten nested arrays.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a browser console fixture. Apply arrays flatten one level in a browser console fixture. The central question is whether the same rule still governs after the context changes. An array returned by the mapper supplies its elements as inner values. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “flatMap flattens the mapper’s returned iterable one level; it does not recursively flatten nested arrays.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Predict the exact brackets in the result before running. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. Only the outer returned iterable is consumed; its direct elements are arrays and remain arrays. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Have the learner draw outer, inner and nested layers. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain arrays flatten one level, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Strings are primitive mapper results and are rejected · Full contents · Next: Generator objects are natural inner iterables →
CHAPTER 8 OF 20 · Back to contents
8. Generator objects are natural inner iterables
The short answer: A mapper can return a generator object to compute inner values on demand. The governing rule is: Inner generator execution advances only as output is requested.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
The helper obtains the generator’s iterator and yields from it before returning to the outer source. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the generator objects are natural inner iterables example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
function* expand(n){ yield n; yield n*n; }
const out=Iterator.from([2,3]).flatMap(expand);
console.log(out.toArray());
Expected result and reasoning. The output is [2,4,3,9]. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Calling expand eagerly for every source value would lose the streaming model. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Which generator is active at each yielded output?”
- Evidence to collect: logs before each yield and outer mapper call
- Variable to hold constant: the surrounding setup, so the comparison isolates generator objects are natural inner iterables.
- Variable to change: consume one value at a time with next()
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For generator objects are natural inner iterables, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a nested collection. Apply generator objects are natural inner iterables in a nested collection. The central question is whether the same rule still governs after the context changes. A mapper can return a generator object to compute inner values on demand. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Inner generator execution advances only as output is requested.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a generator exercise. Apply generator objects are natural inner iterables in a generator exercise. The central question is whether the same rule still governs after the context changes. A mapper can return a generator object to compute inner values on demand. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Inner generator execution advances only as output is requested.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: an infinite sequence. Apply generator objects are natural inner iterables in an infinite sequence. The central question is whether the same rule still governs after the context changes. A mapper can return a generator object to compute inner values on demand. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Inner generator execution advances only as output is requested.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a Node command-line script. Apply generator objects are natural inner iterables in a Node command-line script. The central question is whether the same rule still governs after the context changes. A mapper can return a generator object to compute inner values on demand. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Inner generator execution advances only as output is requested.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Instrument expand and show the event order for the first three outputs. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. The first inner generator yields 2 then 4; only then does the mapper receive 3 and create the second generator. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Use logs sparingly so the temporal sequence remains readable. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain generator objects are natural inner iterables, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Arrays flatten one level · Full contents · Next: Output order is depth-first by outer item →
CHAPTER 9 OF 20 · Back to contents
9. Output order is depth-first by outer item
The short answer: flatMap drains the current inner iterator before advancing the outer iterator. The governing rule is: All inner values for one outer item appear before mapped values from the next outer item.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
The algorithm runs an inner repeat loop and returns to the outer repeat only after the inner iterator is done. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the output order is depth-first by outer item example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
const out=Iterator.from(['A','B']).flatMap(x=>[x+'1',x+'2']);
console.log(out.toArray());
Expected result and reasoning. The order is A1,A2,B1,B2, not A1,B1,A2,B2. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Expecting round-robin interleaving confuses flatMap with a merge scheduler. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Has the current inner iterator finished?”
- Evidence to collect: event log for outer mapper and inner yields
- Variable to hold constant: the surrounding setup, so the comparison isolates output order is depth-first by outer item.
- Variable to change: make the first inner iterable longer
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For output order is depth-first by outer item, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a small data pipeline. Apply output order is depth-first by outer item in a small data pipeline. The central question is whether the same rule still governs after the context changes. flatMap drains the current inner iterator before advancing the outer iterator. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “All inner values for one outer item appear before mapped values from the next outer item.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a paginated result stream. Apply output order is depth-first by outer item in a paginated result stream. The central question is whether the same rule still governs after the context changes. flatMap drains the current inner iterator before advancing the outer iterator. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “All inner values for one outer item appear before mapped values from the next outer item.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a browser console fixture. Apply output order is depth-first by outer item in a browser console fixture. The central question is whether the same rule still governs after the context changes. flatMap drains the current inner iterator before advancing the outer iterator. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “All inner values for one outer item appear before mapped values from the next outer item.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a validation pipeline. Apply output order is depth-first by outer item in a validation pipeline. The central question is whether the same rule still governs after the context changes. flatMap drains the current inner iterator before advancing the outer iterator. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “All inner values for one outer item appear before mapped values from the next outer item.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Contrast depth-first flatMap order with a hypothetical interleaving operator. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. flatMap preserves outer order and drains each mapped iterable; it is not concurrent or round-robin. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Ask for a timeline, not just the final array. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain output order is depth-first by outer item, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Generator objects are natural inner iterables · Full contents · Next: Laziness can avoid unnecessary mapping →
CHAPTER 10 OF 20 · Back to contents
10. Laziness can avoid unnecessary mapping
The short answer: Creating the helper does not immediately traverse the source. The governing rule is: The mapper runs only when a consumer requests outputs.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
Iterator helpers return lazy helper objects. This enables bounded work on large or infinite sources. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the laziness can avoid unnecessary mapping example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
let calls=0;
const h=Iterator.from([1,2]).flatMap(n=>{calls++; return [n];});
console.log(calls);
console.log(h.next().value,calls);
Expected result and reasoning. The first log is 0. After next(), the value is 1 and calls is 1. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Assuming the chain behaves like Array.prototype.flatMap leads to premature side effects. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “What operation actually begins consumption?”
- Evidence to collect: call counter before and after next
- Variable to hold constant: the surrounding setup, so the comparison isolates laziness can avoid unnecessary mapping.
- Variable to change: construct helper but never consume it
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For laziness can avoid unnecessary mapping, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a generator exercise. Apply laziness can avoid unnecessary mapping in a generator exercise. The central question is whether the same rule still governs after the context changes. Creating the helper does not immediately traverse the source. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The mapper runs only when a consumer requests outputs.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: an infinite sequence. Apply laziness can avoid unnecessary mapping in an infinite sequence. The central question is whether the same rule still governs after the context changes. Creating the helper does not immediately traverse the source. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The mapper runs only when a consumer requests outputs.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a Node command-line script. Apply laziness can avoid unnecessary mapping in a Node command-line script. The central question is whether the same rule still governs after the context changes. Creating the helper does not immediately traverse the source. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The mapper runs only when a consumer requests outputs.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a nested collection. Apply laziness can avoid unnecessary mapping in a nested collection. The central question is whether the same rule still governs after the context changes. Creating the helper does not immediately traverse the source. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The mapper runs only when a consumer requests outputs.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Predict mapper calls after construction, one next and full toArray. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. They are 0, then 1, then 2 for this source. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Make the learner separate helper construction from consumption. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain laziness can avoid unnecessary mapping, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Output order is depth-first by outer item · Full contents · Next: Partial consumption preserves the remaining iterator state →
CHAPTER 11 OF 20 · Back to contents
11. Partial consumption preserves the remaining iterator state
The short answer: A consumer may stop after some inner values and continue later. The governing rule is: The helper remembers its outer and inner progress between next calls.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
Because the helper is an iterator, each next resumes the suspended algorithm rather than rebuilding the mapping. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the partial consumption preserves the remaining iterator state example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
const h=Iterator.from([2,3]).flatMap(n=>[n,n*10]);
console.log(h.next());
console.log(h.next());
console.log(h.next());
Expected result and reasoning. The values are 2,20,3 with done false. The third call advances to the second outer item. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Assuming each next remaps from the beginning would duplicate earlier values. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Which outer and inner positions are suspended after each call?”
- Evidence to collect: successive next results and mapper log
- Variable to hold constant: the surrounding setup, so the comparison isolates partial consumption preserves the remaining iterator state.
- Variable to change: pause after the first value then resume
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For partial consumption preserves the remaining iterator state, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a paginated result stream. Apply partial consumption preserves the remaining iterator state in a paginated result stream. The central question is whether the same rule still governs after the context changes. A consumer may stop after some inner values and continue later. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The helper remembers its outer and inner progress between next calls.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a browser console fixture. Apply partial consumption preserves the remaining iterator state in a browser console fixture. The central question is whether the same rule still governs after the context changes. A consumer may stop after some inner values and continue later. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The helper remembers its outer and inner progress between next calls.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a validation pipeline. Apply partial consumption preserves the remaining iterator state in a validation pipeline. The central question is whether the same rule still governs after the context changes. A consumer may stop after some inner values and continue later. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The helper remembers its outer and inner progress between next calls.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a small data pipeline. Apply partial consumption preserves the remaining iterator state in a small data pipeline. The central question is whether the same rule still governs after the context changes. A consumer may stop after some inner values and continue later. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “The helper remembers its outer and inner progress between next calls.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Draw the saved state after yielding 2. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. The current inner array still has 20 remaining, while the outer iterator has not yet requested 3. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
This is a useful mental model for debugging pipelines that appear to “pause”. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain partial consumption preserves the remaining iterator state, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Laziness can avoid unnecessary mapping · Full contents · Next: take() can bound an infinite expansion →
CHAPTER 12 OF 20 · Back to contents
12. take() can bound an infinite expansion
The short answer: A downstream bounded helper can make an infinite source safe to inspect. The governing rule is: Only the outputs needed by the consumer should be produced.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
Laziness composes: flatMap supplies values as take requests them and then closes the chain when the limit is reached. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the take() can bound an infinite expansion example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
function* naturals(){let n=1; while(true) yield n++;}
console.log(Iterator.from(naturals()).flatMap(n=>[n,-n]).take(5).toArray());
Expected result and reasoning. The result is [1,-1,2,-2,3]. The pipeline does not attempt to exhaust naturals. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Calling toArray before take would never finish on the infinite source. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Where is the bounding consumer placed in the chain?”
- Evidence to collect: operator order and number of mapper calls
- Variable to hold constant: the surrounding setup, so the comparison isolates take() can bound an infinite expansion.
- Variable to change: move take before flatMap and compare meaning
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For take() can bound an infinite expansion, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: an infinite sequence. Apply take() can bound an infinite expansion in an infinite sequence. The central question is whether the same rule still governs after the context changes. A downstream bounded helper can make an infinite source safe to inspect. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Only the outputs needed by the consumer should be produced.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a Node command-line script. Apply take() can bound an infinite expansion in a Node command-line script. The central question is whether the same rule still governs after the context changes. A downstream bounded helper can make an infinite source safe to inspect. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Only the outputs needed by the consumer should be produced.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a nested collection. Apply take() can bound an infinite expansion in a nested collection. The central question is whether the same rule still governs after the context changes. A downstream bounded helper can make an infinite source safe to inspect. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Only the outputs needed by the consumer should be produced.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a generator exercise. Apply take() can bound an infinite expansion in a generator exercise. The central question is whether the same rule still governs after the context changes. A downstream bounded helper can make an infinite source safe to inspect. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Only the outputs needed by the consumer should be produced.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Compare take(5) after flatMap with take(5) before flatMap. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. After flatMap it limits outputs to five; before flatMap it limits outer inputs to five and may produce ten outputs. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Use exact operator order as part of the prediction. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain take() can bound an infinite expansion, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Partial consumption preserves the remaining iterator state · Full contents · Next: Zero-output mapping filters while mapping →
CHAPTER 13 OF 20 · Back to contents
13. Zero-output mapping filters while mapping
The short answer: Returning an empty iterable contributes no outputs for that outer value. The governing rule is: An empty inner iterable is valid and simply finishes immediately.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
This lets flatMap combine filtering and expansion while preserving a single lazy pass. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the zero-output mapping filters while mapping example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
const out=Iterator.from([1,2,3,4]).flatMap(n=>n%2?[n]:[]);
console.log(out.toArray());
Expected result and reasoning. The result is [1,3]. Even values are mapped but their empty arrays yield nothing. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Saying the mapper was not called for filtered values is incorrect. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Was the outer value skipped before mapping or mapped to zero outputs?”
- Evidence to collect: mapper-call log and result
- Variable to hold constant: the surrounding setup, so the comparison isolates zero-output mapping filters while mapping.
- Variable to change: return two outputs for odd values
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For zero-output mapping filters while mapping, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a browser console fixture. Apply zero-output mapping filters while mapping in a browser console fixture. The central question is whether the same rule still governs after the context changes. Returning an empty iterable contributes no outputs for that outer value. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “An empty inner iterable is valid and simply finishes immediately.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a validation pipeline. Apply zero-output mapping filters while mapping in a validation pipeline. The central question is whether the same rule still governs after the context changes. Returning an empty iterable contributes no outputs for that outer value. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “An empty inner iterable is valid and simply finishes immediately.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a small data pipeline. Apply zero-output mapping filters while mapping in a small data pipeline. The central question is whether the same rule still governs after the context changes. Returning an empty iterable contributes no outputs for that outer value. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “An empty inner iterable is valid and simply finishes immediately.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a paginated result stream. Apply zero-output mapping filters while mapping in a paginated result stream. The central question is whether the same rule still governs after the context changes. Returning an empty iterable contributes no outputs for that outer value. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “An empty inner iterable is valid and simply finishes immediately.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Instrument calls and show that all four outer values reach the mapper. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. The mapper runs four times; two calls return empty iterables. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
This distinction matters when mapper work has cost or side effects. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain zero-output mapping filters while mapping, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: take() can bound an infinite expansion · Full contents · Next: Mapper errors terminate the helper →
CHAPTER 14 OF 20 · Back to contents
14. Mapper errors terminate the helper
The short answer: If the mapper throws, iteration fails at that outer value. The governing rule is: Abrupt completion is propagated and the outer iterator is closed as specified.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
The algorithm guards mapper evaluation so errors trigger iterator-closing behaviour rather than silently skipping the value. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the mapper errors terminate the helper example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
function* src(){try{yield 1;yield 2;}finally{console.log('outer closed')}}
try{ Iterator.from(src()).flatMap(n=>{if(n===2)throw Error('boom');return [n]}).toArray(); }catch(e){console.log(e.message)}
Expected result and reasoning. The verified fixture yields the first value internally, then prints outer closed and boom when the mapper throws for 2. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Catching the error and continuing as though the same helper were healthy is not the defined recovery model. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Did the error come from outer next, mapper evaluation or inner iteration?”
- Evidence to collect: event log and stack location
- Variable to hold constant: the surrounding setup, so the comparison isolates mapper errors terminate the helper.
- Variable to change: throw from the mapper on a different index
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For mapper errors terminate the helper, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a Node command-line script. Apply mapper errors terminate the helper in a Node command-line script. The central question is whether the same rule still governs after the context changes. If the mapper throws, iteration fails at that outer value. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Abrupt completion is propagated and the outer iterator is closed as specified.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a nested collection. Apply mapper errors terminate the helper in a nested collection. The central question is whether the same rule still governs after the context changes. If the mapper throws, iteration fails at that outer value. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Abrupt completion is propagated and the outer iterator is closed as specified.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a generator exercise. Apply mapper errors terminate the helper in a generator exercise. The central question is whether the same rule still governs after the context changes. If the mapper throws, iteration fails at that outer value. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Abrupt completion is propagated and the outer iterator is closed as specified.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: an infinite sequence. Apply mapper errors terminate the helper in an infinite sequence. The central question is whether the same rule still governs after the context changes. If the mapper throws, iteration fails at that outer value. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Abrupt completion is propagated and the outer iterator is closed as specified.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Explain why the generator’s finally block runs. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. The flatMap algorithm closes the outer iterator on mapper abrupt completion, which enters the generator’s finally block. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Use cleanup logs to make resource behaviour observable. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain mapper errors terminate the helper, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Zero-output mapping filters while mapping · Full contents · Next: Inner iterator errors propagate and trigger cleanup →
CHAPTER 15 OF 20 · Back to contents
15. Inner iterator errors propagate and trigger cleanup
The short answer: An error while advancing the mapped iterable terminates the flatMap operation. The governing rule is: Abrupt inner iteration closes relevant iterators according to the specification.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
The helper cannot manufacture a next value after the inner iterator itself fails; cleanup and error propagation preserve iterator protocol obligations. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the inner iterator errors propagate and trigger cleanup example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
function* inner(){try{yield 'ok';throw Error('inner');}finally{console.log('inner closed')}}
try{ console.log(Iterator.from([1]).flatMap(()=>inner()).toArray()); }catch(e){console.log(e.message)}
Expected result and reasoning. The fixture logs inner closed and then inner. No completed array is returned. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Treating a partial list as successful output hides the failed iteration. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Which iterator produced the abrupt completion, and which cleanup ran?”
- Evidence to collect: ordered console events
- Variable to hold constant: the surrounding setup, so the comparison isolates inner iterator errors propagate and trigger cleanup.
- Variable to change: make the outer source a generator with its own finally
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For inner iterator errors propagate and trigger cleanup, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a validation pipeline. Apply inner iterator errors propagate and trigger cleanup in a validation pipeline. The central question is whether the same rule still governs after the context changes. An error while advancing the mapped iterable terminates the flatMap operation. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Abrupt inner iteration closes relevant iterators according to the specification.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a small data pipeline. Apply inner iterator errors propagate and trigger cleanup in a small data pipeline. The central question is whether the same rule still governs after the context changes. An error while advancing the mapped iterable terminates the flatMap operation. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Abrupt inner iteration closes relevant iterators according to the specification.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a paginated result stream. Apply inner iterator errors propagate and trigger cleanup in a paginated result stream. The central question is whether the same rule still governs after the context changes. An error while advancing the mapped iterable terminates the flatMap operation. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Abrupt inner iteration closes relevant iterators according to the specification.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a browser console fixture. Apply inner iterator errors propagate and trigger cleanup in a browser console fixture. The central question is whether the same rule still governs after the context changes. An error while advancing the mapped iterable terminates the flatMap operation. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Abrupt inner iteration closes relevant iterators according to the specification.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Add outer cleanup instrumentation and predict the order. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. The inner error propagates; cleanup should be observed rather than inferred from a missing array. Record the runtime’s ordered events. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Have the learner preserve failing fixtures; cleanup bugs are often temporal. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain inner iterator errors propagate and trigger cleanup, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Mapper errors terminate the helper · Full contents · Next: Early consumer stop closes active work →
CHAPTER 16 OF 20 · Back to contents
16. Early consumer stop closes active work
The short answer: A consumer that stops early can cause return-based cleanup of the helper chain. The governing rule is: Iterator helpers must cooperate with iterator closing rather than abandon active generators.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
Operations such as take or an explicit return signal termination while an inner iterator may still have values. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the early consumer stop closes active work example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
function* inner(){try{yield 1;yield 2;}finally{console.log('inner cleanup')}}
console.log(Iterator.from([0]).flatMap(()=>inner()).take(1).toArray());
Expected result and reasoning. The result is [1], and the verified runtime runs the inner cleanup when the bounded consumer stops. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Assuming unused generator frames require no cleanup can leak resources in more realistic iterators. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Which iterator is active when the consumer reaches its limit?”
- Evidence to collect: result plus finally log
- Variable to hold constant: the surrounding setup, so the comparison isolates early consumer stop closes active work.
- Variable to change: replace take(1) with full toArray
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For early consumer stop closes active work, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a nested collection. Apply early consumer stop closes active work in a nested collection. The central question is whether the same rule still governs after the context changes. A consumer that stops early can cause return-based cleanup of the helper chain. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Iterator helpers must cooperate with iterator closing rather than abandon active generators.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a generator exercise. Apply early consumer stop closes active work in a generator exercise. The central question is whether the same rule still governs after the context changes. A consumer that stops early can cause return-based cleanup of the helper chain. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Iterator helpers must cooperate with iterator closing rather than abandon active generators.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: an infinite sequence. Apply early consumer stop closes active work in an infinite sequence. The central question is whether the same rule still governs after the context changes. A consumer that stops early can cause return-based cleanup of the helper chain. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Iterator helpers must cooperate with iterator closing rather than abandon active generators.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a Node command-line script. Apply early consumer stop closes active work in a Node command-line script. The central question is whether the same rule still governs after the context changes. A consumer that stops early can cause return-based cleanup of the helper chain. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Iterator helpers must cooperate with iterator closing rather than abandon active generators.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Compare natural completion with early closing. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. Both can execute finally, but the cause differs: one exhausts the generator and one signals early termination. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Connect this model to file handles or cursors without claiming every iterator owns such a resource. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain early consumer stop closes active work, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Inner iterator errors propagate and trigger cleanup · Full contents · Next: Infinite inner iterables can starve later outer values →
CHAPTER 17 OF 20 · Back to contents
17. Infinite inner iterables can starve later outer values
The short answer: flatMap drains each inner iterator, so an infinite first inner iterator prevents the outer iterator from reaching later values. The governing rule is: Depth-first flattening means later outer items wait for current inner completion.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
Laziness prevents eager hanging at construction, but it does not create fairness between inner iterators. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the infinite inner iterables can starve later outer values example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
function* forever(n){while(true)yield n;}
const h=Iterator.from([1,2]).flatMap(forever).take(4);
console.log(h.toArray());
Expected result and reasoning. The output is [1,1,1,1]; outer value 2 is never requested within the bounded consumption. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Expecting [1,2,1,2] assumes interleaving that flatMap does not provide. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Can the current inner iterator ever become done?”
- Evidence to collect: outer mapper log and first outputs
- Variable to hold constant: the surrounding setup, so the comparison isolates infinite inner iterables can starve later outer values.
- Variable to change: make each inner iterable finite
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For infinite inner iterables can starve later outer values, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a small data pipeline. Apply infinite inner iterables can starve later outer values in a small data pipeline. The central question is whether the same rule still governs after the context changes. flatMap drains each inner iterator, so an infinite first inner iterator prevents the outer iterator from reaching later values. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Depth-first flattening means later outer items wait for current inner completion.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a paginated result stream. Apply infinite inner iterables can starve later outer values in a paginated result stream. The central question is whether the same rule still governs after the context changes. flatMap drains each inner iterator, so an infinite first inner iterator prevents the outer iterator from reaching later values. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Depth-first flattening means later outer items wait for current inner completion.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a browser console fixture. Apply infinite inner iterables can starve later outer values in a browser console fixture. The central question is whether the same rule still governs after the context changes. flatMap drains each inner iterator, so an infinite first inner iterator prevents the outer iterator from reaching later values. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Depth-first flattening means later outer items wait for current inner completion.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a validation pipeline. Apply infinite inner iterables can starve later outer values in a validation pipeline. The central question is whether the same rule still governs after the context changes. flatMap drains each inner iterator, so an infinite first inner iterator prevents the outer iterator from reaching later values. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Depth-first flattening means later outer items wait for current inner completion.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Explain what change would allow outer value 2 to appear. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. Return a finite iterable such as [n,n]; once it is exhausted, flatMap advances the outer source. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
This is a clear transfer from order rules to performance and liveness. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain infinite inner iterables can starve later outer values, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Early consumer stop closes active work · Full contents · Next: flatMap versus map →
CHAPTER 18 OF 20 · Back to contents
18. flatMap versus map
The short answer: map yields one mapped value per outer item; flatMap yields values from each mapped iterable. The governing rule is: Choose flatMap only when the mapper intentionally returns an iterable to be flattened one level.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
With map, an array result stays an array value. With flatMap, the array becomes a source of outputs. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the flatmap versus map example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
const a=Iterator.from([1,2]).map(n=>[n,n]);
const b=Iterator.from([1,2]).flatMap(n=>[n,n]);
console.log(a.toArray());
console.log(b.toArray());
Expected result and reasoning. map produces [[1,1],[2,2]]; flatMap produces [1,1,2,2]. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Adding flatMap merely to remove brackets can obscure the intended data model. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Should each mapped iterable remain a value or become part of the output stream?”
- Evidence to collect: exact output shape
- Variable to hold constant: the surrounding setup, so the comparison isolates flatmap versus map.
- Variable to change: change mapper result to a Set
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For flatmap versus map, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a generator exercise. Apply flatmap versus map in a generator exercise. The central question is whether the same rule still governs after the context changes. map yields one mapped value per outer item; flatMap yields values from each mapped iterable. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Choose flatMap only when the mapper intentionally returns an iterable to be flattened one level.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: an infinite sequence. Apply flatmap versus map in an infinite sequence. The central question is whether the same rule still governs after the context changes. map yields one mapped value per outer item; flatMap yields values from each mapped iterable. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Choose flatMap only when the mapper intentionally returns an iterable to be flattened one level.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a Node command-line script. Apply flatmap versus map in a Node command-line script. The central question is whether the same rule still governs after the context changes. map yields one mapped value per outer item; flatMap yields values from each mapped iterable. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Choose flatMap only when the mapper intentionally returns an iterable to be flattened one level.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a nested collection. Apply flatmap versus map in a nested collection. The central question is whether the same rule still governs after the context changes. map yields one mapped value per outer item; flatMap yields values from each mapped iterable. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Choose flatMap only when the mapper intentionally returns an iterable to be flattened one level.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Choose map or flatMap for retaining groups versus emitting their members. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. Use map when group identity matters; use flatMap when members should enter one output sequence. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Ask learners to sketch the desired output shape before selecting a helper. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain flatmap versus map, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: Infinite inner iterables can starve later outer values · Full contents · Next: flatMap versus eager Array.flatMap →
CHAPTER 19 OF 20 · Back to contents
19. flatMap versus eager Array.flatMap
The short answer: The names are similar, but iterator flatMap is lazy and consumes a one-shot iterator. The governing rule is: Do not transfer eager-array assumptions about repeatability and immediate side effects.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
Array.flatMap returns an array immediately after traversing the array. Iterator flatMap returns a helper whose consumption drives work. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the flatmap versus eager array.flatmap example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
let log=[];
const arr=[1,2].flatMap(n=>{log.push(n);return[n]});
console.log(log);
log=[];
const it=Iterator.from([1,2]).flatMap(n=>{log.push(n);return[n]});
console.log(log); it.next(); console.log(log);
Expected result and reasoning. The array version logs [1,2] immediately. The iterator version logs [], then [1] after one next. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Using identical method names as proof of identical evaluation timing is a category error. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “Is the receiver an Array or an Iterator helper?”
- Evidence to collect: log timing and receiver identity
- Variable to hold constant: the surrounding setup, so the comparison isolates flatmap versus eager array.flatmap.
- Variable to change: consume the rest of the iterator
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For flatmap versus eager array.flatmap, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: a paginated result stream. Apply flatmap versus eager array.flatmap in a paginated result stream. The central question is whether the same rule still governs after the context changes. The names are similar, but iterator flatMap is lazy and consumes a one-shot iterator. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Do not transfer eager-array assumptions about repeatability and immediate side effects.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a browser console fixture. Apply flatmap versus eager array.flatmap in a browser console fixture. The central question is whether the same rule still governs after the context changes. The names are similar, but iterator flatMap is lazy and consumes a one-shot iterator. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Do not transfer eager-array assumptions about repeatability and immediate side effects.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a validation pipeline. Apply flatmap versus eager array.flatmap in a validation pipeline. The central question is whether the same rule still governs after the context changes. The names are similar, but iterator flatMap is lazy and consumes a one-shot iterator. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Do not transfer eager-array assumptions about repeatability and immediate side effects.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a small data pipeline. Apply flatmap versus eager array.flatmap in a small data pipeline. The central question is whether the same rule still governs after the context changes. The names are similar, but iterator flatMap is lazy and consumes a one-shot iterator. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Do not transfer eager-array assumptions about repeatability and immediate side effects.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Write a side-effect-free explanation of the timing difference. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. Array computation is eager; iterator helper computation is demand-driven. Prefer pure mappers so timing surprises have less impact. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Teach the semantic difference before performance claims. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain flatmap versus eager array.flatmap, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: flatMap versus map · Full contents · Next: Choosing flatMap for the right pipeline →
CHAPTER 20 OF 20 · Back to contents
20. Choosing flatMap for the right pipeline
The short answer: Use flatMap when a lazy outer sequence must expand each item into an object iterable and preserve depth-first order. The governing rule is: Reject it when recursive flattening, round-robin merging, eager reuse or primitive mapper results are required.. This is the sentence a learner should be able to say before touching a keyboard. It turns a vague topic into a testable model and gives a parent or tutor something precise to listen for.
A good choice accounts for output shape, source finiteness, cleanup and runtime support. That mechanism matters because superficially similar examples can produce different results. A reliable explanation names the relevant object, identifies the operation performed on it, and states when the decision is made. “It works” is not enough; mastery means predicting the result and explaining why a nearby example behaves differently.
Worked example: predict before running
Read the choosing flatmap for the right pipeline example once without executing it. Mark the exact input, the operation under study, and the expected observable result. Then write a one-sentence prediction. Only after that should the learner run the example. This order separates understanding from trial-and-error and makes any surprise diagnostically useful.
const words=Iterator.from([['learn','well'],[],['teach']]);
console.log(words.flatMap(group=>group).toArray());
Expected result and reasoning. The result is [‘learn’,’well’,’teach’]; the empty group contributes nothing. The important evidence is not merely the printed value or exit status. It is the connection between that evidence and the rule above. Say the chain aloud: input → relevant rule → operation → observable result. If a learner cannot supply the middle two links, the right response is to revisit the model rather than add more examples.
Near miss. Choosing the helper before defining desired order and termination can produce a pipeline that is correct syntactically but wrong operationally. This is tempting because it uses a familiar word or visual resemblance. Correct it by changing only one variable at a time and comparing the two cases side by side. A good contrast preserves everything except the feature named in the rule.
Diagnostic route when the answer is wrong
Use a four-pass diagnosis. Pass one: classify. Identify the kind of value or state being examined. Pass two: trace. Follow the operation in the order defined by the platform or specification. Pass three: observe. Capture a minimal output, not a screenshot of a large project. Pass four: contrast. Change one feature and run again. For this chapter, the highest-value question is: “What output shape, order and stopping condition does the application need?”
- Evidence to collect: source type, mapped type, consumer and version
- Variable to hold constant: the surrounding setup, so the comparison isolates choosing flatmap for the right pipeline.
- Variable to change: replace a finite group with an infinite generator
- Explanation standard: name the rule, not merely the successful command or copied syntax.
For choosing flatmap for the right pipeline, a common unproductive move is to make several changes at once. That can make the symptom disappear while leaving the misconception intact. Reset to the smallest example, keep a brief prediction log, and preserve both the successful and unsuccessful case. The pair becomes a reusable test fixture and a much clearer revision note than a paragraph of definitions.
Four transfer cases
Transfer case 1: an infinite sequence. Apply choosing flatmap for the right pipeline in an infinite sequence. The central question is whether the same rule still governs after the context changes. Use flatMap when a lazy outer sequence must expand each item into an object iterable and preserve depth-first order. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Reject it when recursive flattening, round-robin merging, eager reuse or primitive mapper results are required.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 2: a Node command-line script. Apply choosing flatmap for the right pipeline in a Node command-line script. The central question is whether the same rule still governs after the context changes. Use flatMap when a lazy outer sequence must expand each item into an object iterable and preserve depth-first order. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Reject it when recursive flattening, round-robin merging, eager reuse or primitive mapper results are required.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 3: a nested collection. Apply choosing flatmap for the right pipeline in a nested collection. The central question is whether the same rule still governs after the context changes. Use flatMap when a lazy outer sequence must expand each item into an object iterable and preserve depth-first order. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Reject it when recursive flattening, round-robin merging, eager reuse or primitive mapper results are required.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Transfer case 4: a generator exercise. Apply choosing flatmap for the right pipeline in a generator exercise. The central question is whether the same rule still governs after the context changes. Use flatMap when a lazy outer sequence must expand each item into an object iterable and preserve depth-first order. Preserve a tiny record of input, prediction and observed result so that an apparent exception can be investigated rather than guessed at. Start by naming the observable evidence, then apply the chapter rule “Reject it when recursive flattening, round-robin merging, eager reuse or primitive mapper results are required.”. Do not jump straight to a command or syntax change. First predict the outcome, perform the smallest safe check, and compare the result with that prediction. This makes the case useful beyond the immediate exercise: the learner is practising a decision process, not memorising a one-off answer. If the result differs, record what changed—platform, input shape, repository state, document tree, or evaluation order—before revising the model.
Practice, pause point, and explained answer
Task. Decide whether flatMap fits token groups, concurrent streams and recursive tree flattening. Before checking anything, write (1) the predicted result, (2) the rule that justifies it, and (3) one nearby variation that should change the result. A complete response should be understandable to someone who has not seen the example.
Explained answer. It fits ordered iterable groups; it is not a concurrency merge and does not recursively traverse trees without explicit logic. The reasoning earns more attention than the final value. If the learner reached the correct result by guessing, repeat the task with the variation they proposed. If they can predict both cases and explain the contrast, the idea is beginning to transfer.
Parent and tutor decision point
Request a decision memo with one reason to use the helper and one reason not to. A useful conversation is brief: ask for the rule, ask for a prediction, then ask which observation would disprove it. Avoid turning the exchange into a vocabulary quiz. The goal is to hear a causal explanation and see a controlled test. Praise a corrected prediction when the learner uses evidence well; that is stronger progress than protecting an unexamined first answer.
Ready to move on? Move forward when the learner can explain choosing flatmap for the right pipeline, solve the worked case without prompts, and handle at least two transfer cases with a changed context. Revisit this chapter when the explanation relies on “usually”, “looks like”, or “the computer says so” without identifying the governing rule.
← Previous: flatMap versus eager Array.flatMap · Full contents · Parent guide →
Parent guide: what mastery looks like
A learner has not mastered JavaScript Iterator.prototype.flatMap merely because one polished example runs. Look for four behaviours: they can state the rule in plain language; predict before executing; isolate one changed condition; and explain why a transfer case is the same problem or a different one. Those behaviours make progress visible without requiring a parent to become a specialist.
Use a ten-minute check-in. Ask the learner to choose one chapter, reconstruct its example from memory, and narrate the causal chain. Then change one input. If the learner can update the prediction and justify the change, stop. More repetitions are not automatically better. Save the two-case pair and return to it after a few days.
If every answer is hesitant, reduce the scope. Return to the earliest chapter whose rule cannot be stated accurately. If explanations are fluent but real tasks still fail, move to a capstone because the missing skill is likely transfer or diagnosis. If frustration rises, separate typing errors from conceptual errors and solve only one category in that session.
Capstone practice with explained routes
Capstone 1: Rebuild the smallest trustworthy fixture
Scenario. Create a disposable JavaScript fixture that demonstrates lazy iterator expansion without unrelated project code.
Route. Record environment, input, prediction and output. Keep one nearby contrast. Begin with a written prediction, collect the smallest sufficient evidence, and explain which observation would make you revise the conclusion.
Explained resolution. The fixture is successful when another learner can reproduce the observation and explain the rule that separates the two cases. A strong submission includes the result, the causal chain and a controlled contrasting case. It does not hide uncertainty: if platform, version or environment matters, state that boundary.
Capstone 2: Diagnose a believable wrong explanation
Scenario. A learner has the correct output but explains it using the wrong mechanism.
Route. Change the one condition that the wrong explanation says should matter, while holding the real governing condition constant. Begin with a written prediction, collect the smallest sufficient evidence, and explain which observation would make you revise the conclusion.
Explained resolution. If the prediction based on the wrong mechanism fails and the rule-based prediction holds, the contrast exposes the misconception. A strong submission includes the result, the causal chain and a controlled contrasting case. It does not hide uncertainty: if platform, version or environment matters, state that boundary.
Capstone 3: Handle an environment boundary
Scenario. Two machines or runtimes produce different observations.
Route. Capture versions, platform or browser, exact input and relevant state before comparing. Begin with a written prediction, collect the smallest sufficient evidence, and explain which observation would make you revise the conclusion.
Explained resolution. A difference is not automatically an error. Use the primary source to identify versioned or environmental conditions, then retest. A strong submission includes the result, the causal chain and a controlled contrasting case. It does not hide uncertainty: if platform, version or environment matters, state that boundary.
Capstone 4: Design a parent check-in
Scenario. A parent has ten minutes and no specialist background.
Route. Ask for one rule, one prediction, one run and one changed condition. Begin with a written prediction, collect the smallest sufficient evidence, and explain which observation would make you revise the conclusion.
Explained resolution. The learner demonstrates mastery by explaining the causal chain and revising from evidence, not by performing a long polished demo. A strong submission includes the result, the causal chain and a controlled contrasting case. It does not hide uncertainty: if platform, version or environment matters, state that boundary.
Capstone 5: Transfer into a larger project
Scenario. The isolated fixture works but the school or home project does not.
Route. Preserve the fixture, then compare project inputs and state one dependency at a time. Begin with a written prediction, collect the smallest sufficient evidence, and explain which observation would make you revise the conclusion.
Explained resolution. The first differing dependency that changes the outcome becomes the next diagnostic focus; the verified rule remains the baseline. A strong submission includes the result, the causal chain and a controlled contrasting case. It does not hide uncertainty: if platform, version or environment matters, state that boundary.
Capstone 6: Write a regression check
Scenario. The behaviour must remain understood after a future update.
Route. Save the smallest positive case, the near miss and the version metadata. Begin with a written prediction, collect the smallest sufficient evidence, and explain which observation would make you revise the conclusion.
Explained resolution. A useful regression check fails for a meaningful reason, reports the changed observation and points back to the governing rule. A strong submission includes the result, the causal chain and a controlled contrasting case. It does not hide uncertainty: if platform, version or environment matters, state that boundary.
Capstone 7: Explain a limitation honestly
Scenario. The chosen API or feature does not cover an important edge case.
Route. Name the limitation, show what evidence the tool does provide and identify a more authoritative route. Begin with a written prediction, collect the smallest sufficient evidence, and explain which observation would make you revise the conclusion.
Explained resolution. The final advice is bounded: it neither discards the useful tool nor stretches it into a guarantee it cannot make. A strong submission includes the result, the causal chain and a controlled contrasting case. It does not hide uncertainty: if platform, version or environment matters, state that boundary.
Capstone 8: Choose the right tool
Scenario. Several related methods or commands could appear to solve the same task.
Route. Define desired output, evaluation timing, platform boundary and acceptable failure modes. Begin with a written prediction, collect the smallest sufficient evidence, and explain which observation would make you revise the conclusion.
Explained resolution. Select the tool whose contract matches those needs and state why at least one tempting alternative was rejected. A strong submission includes the result, the causal chain and a controlled contrasting case. It does not hide uncertainty: if platform, version or environment matters, state that boundary.
Frequently asked questions
Is JavaScript Iterator.prototype.flatMap mainly a syntax topic?
No. Syntax is only the visible handle. The durable skill is deciding what the operation means, predicting its boundary conditions, and collecting evidence that distinguishes one explanation from another.
How long should one practice session be?
A focused ten-to-twenty-minute session is enough for one rule, one worked example and one contrast. Stop when the learner can explain the causal chain; save the fixture for later retrieval rather than adding tired repetitions.
Should a learner memorise every edge case?
Memorise the central rule and know where to consult the primary reference. Edge cases should be organised by cause—platform, input type, evaluation order, document tree or repository state—rather than stored as an unconnected list.
What should a parent ask if they do not code?
Ask for a prediction, the rule behind it, the observation that would disprove it, and one changed case. Those questions reveal understanding without requiring the parent to know the final technical answer in advance.
When is copying an example acceptable?
Copying is useful for establishing a trusted baseline. It becomes learning only after the student predicts the result, reconstructs the example, changes one condition and explains the changed outcome.
How can we tell a typing error from a conceptual error?
Run a known-good minimal fixture first. If that fixture fails, inspect setup and transcription. If it passes but the learner predicts the wrong outcome for a controlled variation, the misconception is conceptual.
Should practice happen in a large school project?
Not initially. Large projects contain too many moving parts. Begin in a disposable directory, tiny script or isolated HTML file, then transfer the verified rule into the larger task.
What belongs in revision notes?
Keep the rule in one sentence, a smallest successful example, a near miss, the observed output, the environment version and one diagnostic question. This compact record is more reusable than a page of copied prose.
What if different computers give different results?
Treat the difference as evidence. Record operating system, runtime or browser version, filesystem or repository state, and exact input. Then consult the versioned primary source before deciding that either result is wrong.
When should the learner move to a new topic?
Move on when they can explain the rule, predict two contrasting cases, diagnose a deliberately broken example and transfer the idea to a fresh context without step-by-step prompting.
References and verification notes
Primary technical source: TC39 Iterator Helpers specification for Iterator.prototype.flatMap. The specification defines callable validation, zero-based counter, GetIteratorFlattenable with primitive rejection, lazy inner yielding and iterator closing on abrupt completion.
The worked examples were checked with Node.js v24.19 for laziness, ordering, index, array/generator flattening, primitive rejection, bounded infinite input and cleanup examples. The checks confirm the specific examples in this guide; they do not promise identical behaviour on an older version, a different operating system, a different browser implementation, or a repository with different state. Keep the version and environment with the saved fixture.
Last reviewed: 17 October 2026. This article is educational guidance for families and learners. It does not advertise a physical Punggol outlet or make admissions, affiliation, score or outcome guarantees.

