How to Create a Multiple Counter for a Loop in JavaScript?

Estimated read time 1 min read

To create multiple counters for a loop in JavaScript, you can use separate variables for each counter and increment them independently within the loop.

Here’s an example of how you could create two counters to keep track of the number of odd and even numbers in an array:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let oddCount = 0;
let evenCount = 0;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
  } else {

console.log('Odd count: ' + oddCount);
console.log('Even count: ' + evenCount);

In this example, the oddCount variable is initialized to 0 and the evenCount variable is initialized to 0. The loop iterates over the numbers array and increments the oddCount variable if the current number is odd, and the evenCount variable if the current number is even. Finally, the values of the counters are logged to the console.

You can use this approach to create as many counters as you need, depending on the requirements of your use case.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply