javascriptarraysrecursion

How do I make the array print out in the console log (recursion)


I am doing recursion for the first time in javascript. I made an array and want it to print out every element however it only printso ut the first element (1)

function loop4(){
    arr = [1,2,3,4,5,6,7,8,9,10]
    i=0
    console.log(arr[i])
    i++
    if(i<arr.length){
        loop4(i)
    }
    else{
        return

    }
    
}

loop4()

This is the code for the program

I have looked at it logically and can see where my mistake was. When the loop starts again "i" is set as 0 therefore infintanly printing out "1" How can I upadte the code in order for it to print out an array with recursion ?

I expect the code to print out the array however i am incapible of doing that so any help would be appreciated


Solution

  • You should pass i as a parameter, so it doesn't get reset to 0 on each call. You can use a default value for the initial call.

    There's no need for else { return }, since the function returns automatically.

    function loop4(i = 0) {
      arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      console.log(arr[i])
      i++
      if (i < arr.length) {
        loop4(i)
      }
    }
    
    loop4()