1

I came across something in the uBlock origin source and couldn't find any explanation or documentation on it.

for (;;) {
    pos = content.indexOf(compiledFilter, pos);
    if ( pos === -1 ) { break; }
    // We need an exact match.
    // https://github.com/gorhill/uBlock/issues/1392
    // https://github.com/gorhill/uBlock/issues/835
    const notFound = pos !== 0 &&
                     content.charCodeAt(pos - 1) !== 0x0A;
    pos += compiledFilter.length;
    if (
        notFound ||
        pos !== content.length && content.charCodeAt(pos) !== 0x0A
    ) {
        continue;
    }
}

What exactly does for (;;) do and what benefits does it offer?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Reez0
  • 2,512
  • 2
  • 17
  • 39
  • 6
    It's an infinite loop, just like `while (true)` – Barmar Jan 12 '21 at 06:40
  • 4
    [Duplicate](https://stackoverflow.com/search?tab=votes&q=%5bjs%5d%20code%3a%22for(%3b%3b)%22) of [In JavaScript what does for(;;){...} do?](https://stackoverflow.com/q/4904880/4642212). – Sebastian Simon Jan 12 '21 at 06:45

1 Answers1

3

The syntax of for loop is like

for(initialization; condition; increment/decrement){
}

Now if you want to skip any of those three steps you can just leave its space empty but put the semicolon. In the above example, the user is skipping all three steps.

As mentioned, it will be an infinite loop. If you don't break or return inside the loop, the JavaScript code (and in the browser, the entire tab) will hang with high CPU usage.

Note: I won't recommend using something like this. This is kind of unfamiliar way. while(true){ ... } achieves the same behavior, but is easier to read.

FZs
  • 16,581
  • 13
  • 41
  • 50
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73