I'm new to software development and trying to understand the basics of JavaScript. In the code below, if I write iterator.next() instead of charAt in "while", the result changes. Can you explain this to me why does it only return 1 when I type iterator.next directly?
const str = '123';
const iterator = str[Symbol.iterator]()
let charAt = iterator.next()
while (!charAt.done) {
console.log(charAt.value)
charAt = iterator.next()
// output: "1"
// "2"
// "3"
}
const str = '123';
const iterator = str[Symbol.iterator]()
let charAt = iterator.next()
while (!iterator.next().done) {
console.log(charAt.value)
charAt = iterator.next()
// output: "1"
}
It's easier to see if you have a longer string.
const str = '12345678';
const iterator = str[Symbol.iterator]()
let charAt = iterator.next()
while (!iterator.next().done) {
console.log(charAt.value)
charAt = iterator.next()
// output: "1"
}
Because you call next() in two different places inside the loop (as well as once outside the loop), every time you go around the loop, you advance two places.