How can I run a fixed number of loop iterations in JavaScript while formatting JSON output?

I’m trying to run a loop 10 times that prints a JSON object with a ‘current’ key and, except for the first iteration, includes a ‘total’ property every three iterations. I want to keep it simple with just a for loop.

let currentIndex = 0;
const numbers = [];

function generateRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function createResult(number) {
  numbers.push(number);
  const result = { current: number };
  if (currentIndex > 0 && currentIndex % 3 === 0) {
    const total = numbers.reduce((acc, curr) => acc + curr, 0);
    result.total = total;
  }
  currentIndex++;
  return JSON.stringify(result);
}

for (let j = 0; j < 10; j++) {
  console.log(createResult(generateRandom(0, 1982)));
}

I have frequently used similar techniques. The code snippet appears correct but one suggestion from my own experience is to consider variable scoping carefully, especially with the currentIndex variable. Sometimes, encapsulating loop variables within a function prevents unintentional modifications or race conditions when the code is scaled up in a more asynchronous environment. Also, if readability and maintenance become an issue, refactoring pieces of reusable logic into smaller functions might be preferable. The current approach works well for a simple loop iteration scenario like this.

The snippet works fine, but I would like to share my experience with similar implementations. In my projects I’ve noticed that ensuring proper scoping for variables can reduce potential issues later on, especially when device conditions are introduced within the loop. The global handling of variables such as the current index and the array, while acceptable in this simple case, can lead to unintended behaviors if the code base grows. I tend to isolate the loop’s internals in a dedicated function to keep the state management clear. Also, testing boundary conditions really helped me refine the conditional logic before deployment.