Sometimes, we want to create an array from a generator in JavaScript.
In this article, we’ll look at how to create an array from a generator in JavaScript.
How to create an array from a generator in JavaScript?
To create an array from a generator in JavaScript, we can use the spread operator.
For instance, we write:
function* seq(minVal, maxVal) {
let currVal = minVal;
while (currVal < maxVal) {
yield currVal++;
}
}
const list = [...seq(1, 10)]
console.log(list)
to create the seq
generator function.
Then we call it with 1 and 10 and spread the returned results into an array.
Therefore list
is [1, 2, 3, 4, 5, 6, 7, 8, 9]
.
Conclusion
To create an array from a generator in JavaScript, we can use the spread operator.