Generators in JavaScript
Generators are a feature in JavaScript that allow you to define functions that can be paused and resumed. Generators are useful for writing iterators, which are objects that can produce a sequence of values.
Here's an example of how to use generators in JavaScript:
javascript
function* fibonacci() {
let a = 0;
let b = 1;
while (true) {
let temp = a;
a = b;
b = temp + b;
yield a;
}
}
const fib = fibonacci();
for (let i = 0; i < 10; i++) {
console.log(fib.next().value);
}
This code defines a generator function that produces the Fibonacci sequence and uses a for loop to print the first 10 numbers in the sequence.
No comments:
Post a Comment