-2

I recently came to this thread, and had a quick question on the syntax used in the first answer. @ggorlen used this syntax/notation in the for loop that I've never seen before and couldn't find any answers online:

  for (;;) {
    try {
      await page.waitForFunction(
        `${thumbs.length} !==
          document.querySelectorAll("#video-title").length`, 
        {timeout: 10000}
      );
    }
    catch (err) {
      break;
    }

    thumbs = await page.$$eval("#video-title", els => {
      els.at(-1).scrollIntoView();
      return els.map(e => e.getAttribute("title"));
    });
  }

What does the for(;;) {...} do?

Thanks!

I just have a question on the syntax used, and couldn't find an answer.

jolthedev
  • 11
  • 1
  • 1
    It's a regular `for` loop, however all three parts are empty, so there is no condition under which the loop will ever stop, meaning it's an infinite loop now. – CherryDT Jan 08 '23 at 20:12
  • https://flexiple.com/javascript/infinite-loops-javascript/ – Paul T. Jan 08 '23 at 20:14
  • 1
    [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) This should be the first place when you have a question https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for – jabaa Jan 08 '23 at 20:18
  • See also [What does "for(;;)" mean?](/q/4894120/4642212). – Sebastian Simon Jan 08 '23 at 20:41

1 Answers1

1
for(;;) {
}

is the equivalent of

while (true) {
 }

a normal "for" loop contains 3 parts separated by semi-colons like for(initialization; condition; afterthought)

The initialization runs before the looping starts.

The condition is checked at the beginning of each iteration, and if it evaluates to true, then the code in the loop body executes.

The afterthought is executed at the end of each iteration of the loop.

It is allowed to ommit these parts of the for expression e.g. for(;;) When omitted it essentially means that it will loop forever since the condition is not present or until the code reaches a return or break.

You can read more about the for function checkout this MDN page.

Cody
  • 467
  • 2
  • 11