Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
The yield* expression/keyword in JavaScript.
The yield* expression in JavaScript is used to delegate to another generator function or any iterable object. It yields all values from the delegated generator or iterable, effectively "flattening" nested generators.
Syntax
function* generatorFunction() {
yield* anotherGenerator();
yield* iterableObject;
}
Basic Example: Delegating to Another Generator
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>yield* Example</title>
</head>
<body>
<h1>yield* keyword in JavaScript</h1>
<div id="result"></div>
<button onclick="demonstrateYieldStar()">CLICK HERE</button>
<p>Click the button to see yield* delegation in action</p>
<script>
function* innerGenerator() {
yield 12;
yield 24;
yield 36;
}
function* outerGenerator() {
yield* innerGenerator();
yield 48;
}
function demonstrateYieldStar() {
const iterator = outerGenerator();
const resultDiv = document.getElementById('result');
let output = '';
let result = iterator.next();
while (!result.done) {
output += result.value + '<br>';
result = iterator.next();
}
resultDiv.innerHTML = output;
}
</script>
</body>
</html>
Example: Using yield* with Arrays
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>yield* with Arrays</title>
</head>
<body>
<h1>yield* with Iterable Objects</h1>
<div id="arrayResult"></div>
<button onclick="demonstrateArrayYield()">Iterate Arrays</button>
<script>
function* arrayGenerator() {
yield* [1, 2, 3];
yield* 'ABC';
yield* [4, 5, 6];
}
function demonstrateArrayYield() {
const iterator = arrayGenerator();
const resultDiv = document.getElementById('arrayResult');
let output = '';
for (const value of iterator) {
output += value + ' ';
}
resultDiv.innerHTML = output;
}
</script>
</body>
</html>
Comparison: yield vs yield*
| Expression | Behavior | Use Case |
|---|---|---|
yield |
Yields a single value | Return individual values |
yield* |
Delegates to another generator/iterable | Flatten nested generators or iterate objects |
Key Points
-
yield*can delegate to any iterable object (arrays, strings, other generators) - It passes through all values from the delegated iterable
- The return value of the delegated generator becomes the value of the
yield*expression - Useful for composing generators and creating hierarchical data structures
Conclusion
The yield* expression provides a powerful way to delegate generator execution to other generators or iterables. It enables clean composition of generators and efficient iteration over nested data structures.
Advertisements
