Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
Using a function directly or by declaring it to a variable

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"
  }

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

  • u have used iterator.next() three times,
  • for the fitst time it returs 1, which u assign to charAt,
  • then in while loop condition iterator.next() returns 2, but u have not assigned it any where,
  • and because u have not updated your charAt value yet, it logs 1,
  • then iterator.next() returns 3, which u assign to charAt,
  • but in second pass of while loop iterator.next() returns {done:true}, and the control doesn't goes inside loop
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!