0

Apologies if this is daft question, but I can't understand why the following code logs the letters from a string in a seemingly random order:

const aString = "hello, this is a string";
const iterator = aString[Symbol.iterator]();

var typewriter =
  setInterval(() => {
    if (iterator.next().done) {
      clearInterval(typewriter);
    } else {
      console.log(iterator.next().value);
    }
  }, 200);

1 Answer 1

3

I can't understand why the following code logs the letters from a string in a seemingly random order:

It doesn't, it skips every other character. That's because you are calling .next twice in every iteration. if (iterator.next().done) will consume a character. Only call .next() once:

const aString = "hello, this is a string";
const iterator = aString[Symbol.iterator]();

var typewriter =
  setInterval(() => {
    const next = iterator.next();
    if (next.done) {
      clearInterval(typewriter);
    } else {
      console.log(next.value);
    }
  }, 200);

3
  • Ah! Thank you so much. That makes sense. I'm too much of an amateur to know why that happens, though. If you had time I would really appreciate help understanding that? Apr 30, 2017 at 5:20
  • What specifically do you not understand? Apr 30, 2017 at 5:21
  • At first, I didn't understand why if (iterator.next().done) would constitute a next() call. Seems totally ridiculous now that I think about it but in my head, it didn't make sense that it would 'count', given that my intent was just to use it as a condition for the if...else statement. I am very new to programming and I am not used to there being no implied meaning in things :P Apr 30, 2017 at 5:55

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.