2

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)
}
asked Apr 21, 2020 at 21:16
1
  • 1
    Because you're calling next() twice per iteration of that loop?! Commented Apr 21, 2020 at 21:29

3 Answers 3

5

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);
}

answered Apr 21, 2020 at 21:27
Sign up to request clarification or add additional context in comments.

1 Comment

(in reality you should assign the result of nums.next() to a variable, and then check for its .done property)
3

You call .next() twice per iteration, hence you skip every other number.

answered Apr 21, 2020 at 21:27

1 Comment

Nah, everyone does this kind of mistakes every now and then lol.
1

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);
//}

answered Apr 21, 2020 at 21:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.