Search code examples
javascriptarraysfor-loopinfinite-loop

Output array elements infinitely


I'm trying to output array elements infinitely. I've already found another way to do this, but can you help me understand why the first element doesn't output in this code after the first iteration of array?

li = [1, 2, 3, 4, 5]
  for (i=0; i<li.length; i++) {           
    console.log(li[i])
    if (i+1 == li.length) { 
      i = 0 
}

Expected output: 1 2 3 4 5 1 2 3 4 5 ...

Actual output:

1 2 3 4 5 2 3 4 5 ...

(1 is present olny in the first loop)


Solution

  • Inside a for loop, i++ is executed after each iteration completes. Thus, when i reach the index 4 and trigger the if condition, it's set to 0. Following this, i++ executes, resulting in i becoming 1, leading to a printed value of 2 instead of 1. To address this, you can set i to -1 within the if block to get the desired output.

    Code:

    li = [1, 2, 3, 4, 5]
      for (i=0; i<li.length; i++) {           
            console.log(li[i])
        if (i+1 == li.length) { 
            i = -1 
    }
    }