function*() { .... }
I just found that form of definition in some other js code, what does the star mean indeed? Thanks
In ES2015+, it defines a generator function.
Here's an example of a generator:
function* fibonacci() {
let [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
Various ways to use:
With a for-of
loop (another ES2015+ thing):
for (const n of fibonacci()) {
// truncate the sequence at 1000
if (n > 1000) {
break;
}
console.log(n);
}
Example:
function* fibonacci() {
let [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
for (const n of fibonacci()) {
// truncate the sequence at 1000
if (n > 1000) {
break;
}
console.log(n);
}
.as-console-wrapper {
max-height: 100% !important;
}
Using the iterator directly (for-of
uses it under the covers for you):
const seq = fibonacci();
console.log(seq.next().value); // 1
console.log(seq.next().value); // 2
console.log(seq.next().value); // 3
console.log(seq.next().value); // 5
console.log(seq.next().value); // 8
function* fibonacci() {
let [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
const seq = fibonacci();
console.log(seq.next().value); // 1
console.log(seq.next().value); // 2
console.log(seq.next().value); // 3
console.log(seq.next().value); // 5
console.log(seq.next().value); // 8
.as-console-wrapper {
max-height: 100% !important;
}
From here
A function with a * token is known as a generator function. The following two unary operators are only allowed in the immediate body of a generator function (i.e., in the body but not nested inside another function):
AssignmentExpression:
...
YieldExpression
YieldExpression:
"yield" ("*"? AssignmentExpression)?
An early error is raised if a yield or yield* expression occurs in a non-generator function.
Also check the MDN and What Is This Thing Called Generators?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With