I am new to javascript and can't understand such a behaviour of generator function. Why does it output only odd nums(1,3,5,7,9)?
function* numberGen(n){
for (let i=0;i<n;i++){
yield i
}
}
const num = numberGen(10)
while (num.next().value!=undefined){
console.log(num.next().value)
}
3 Answers 3
You're calling num.next() twice in every iteration. You're calling it once in the while() header to check whether the result is undefined, then you're calling it a second time in the body to log the value. Each call retrieves the next item from the generator. So you check the even items for null, and log the odd item after it.
Instead you should assign a variable to a single call
function* numberGen(n){
for (let i=0;i<n;i++){
yield i
}
}
const num = numberGen(10)
let i;
while ((i = num.next().value) !== undefined){
console.log(i)
}
Instead of calling the .next() method explicitly, you can use the built-in for-of iteration method.
function* numberGen(n) {
for (let i = 0; i < n; i++) {
yield i
}
}
const num = numberGen(10)
for (let i of num) {
console.log(i);
}
1 Comment
nums.next() to a variable, and then check for its .done property)You call .next() twice per iteration, hence you skip every other number.
1 Comment
inside the while condition checking statement you consume one in two value just for checking, iterators are consumable, and that why we just see odd numbers, even number were used for truthy checks
function* numberGen(n){
for (let i=0;i<n;i++){
yield i
}
}
const num = numberGen(10);
//using spread opertaor to iterate all values
console.log([...num]);
//or you can use forOf
//for( number of num ){
// console.log(number);
//}
next()twice per iteration of that loop?!