Search code examples
javascriptfor-loopecmascript-6operatorsecmascript-2016

What is the purpose of for(;;) in the following code snippet?


So, Iwas reading through some Javascript Question answers on CodeGolf to try and improve my understanding of Javascript a lttle bit, & noticed this answer in the following question Generate Green Spraypaint Patterns Within the Answer I spotted a for loop that..[to me] is not the usual Syntax, & no matter how much I stare at it I can't figure out what this does. I can't find any referance to an operator ;; on Mozilla's Javascript Operators page & was wondering if anyone can explain What the double semi-colon does in the code below?

b.onclick = async function() {
  b.disabled = true;
  try {
    await f(c, +s.value, +n.value, +m.value, JSON.parse(d.value));
  } catch (ex) {
    console.error(ex);
  }
  b.disabled = false;
}
async function f(canvas, size, number, moves, deltas) {
  canvas.width = canvas.height = size;
  let context = canvas.getContext('2d', { alpha: false });
  context.fillRect(0, 0, size, size);
  let image = context.getImageData(0, 0, size, size);
  for (let i = 0; i < number; i++) {
    let x = size / 2 | 0, y = x, j = moves;
    for (;;) {
      image.data[(x + y * size) * 4 + 1]++;
      if (!j--) break;
      let valid = deltas.map(([dx, dy]) => [x + dx, y + dy]).filter(([x, y]) => x >= 0 && y >= 0 && x < size && y < size);
      if (!valid.length) break;
      [x, y] = valid[valid.length * Math.random() | 0];
    }
    context.putImageData(image, 0, 0);
    await new Promise(requestAnimationFrame);
  }
}

<div>Size: <input id=s type=number min=1 value=250></div>
<div>Pixels: <input id=n type=number min=0 value=800></div>
<div>Moves: <input id=m type=number min=0 value=7000></div>
<div>Deltas: <input id=d value=[[1,2],[-1,2],[1,-2],[-1,-2],[2,1],[-2,1],[2,-1],[-2,-1]]></div>
<div><input id=b type=button value=Go!></div>
<canvas id=c>

Might be really simple, but just curious to learn. Is it just a placeholder to grab the exact same info from the for loop that its nested with-in?

Just for anyone else's reference, thats beginning or learning Javascript none of the below work.. lol enter image description here


Solution

  • for(;;) is a for loop declaration with:

    • no initialization code
    • no end-of-block expression
    • no terminating condition

    So, it's equivalent to while(true) - it'll loop forever until a break inside it is encountered.