Can generators be used in ES5? Yes, using babel you can transpile them to ES5 JavaScript.
In a normal function, there is only one entry point: the invocation of the function itself. A generator allows you to pause the execution of a function and resume it later. Generators are useful when dealing with iterators and can simplify the asynchronous nature of Javascript.
The function* declaration ( function keyword followed by an asterisk) defines a generator function, which returns a Generator object.
In ECMAScript 2015, generators were introduced to the JavaScript language. A generator is a process that can be paused and resumed and can yield multiple values. A generator in JavaScript consists of a generator function, which returns an iterable Generator object.
What's the correct way of using the new ES5 array functions with ES6 generators? Do I have to explicitly convert the iterable into an array first, or is there a better way? For example:
function* range(low, high) {
var i = low;
while(i < high)
yield i++;
}
// Sum of numbers in range, doesn't work
console.log(range(0, 10).reduce((x,y) => x + y));
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