How is this happening without a loop?
It is using recursion, this means the function itself is called from within the function. Using a loop is not the only way to iterate over a collection.
If you look at your code the print function is called once outside your function, but also inside the print function itself. So when we first run your function with the array [1, 2, 3] we run the function with the following arguments:
print([1, 2, 3], 0, 3)
Then when we enter the function, we look at the if statement and see that pos (0) is in fact less than len (3). So, we then go ahead and console.log(arr[0]) which will print the first item in your array.
We then proceed to the next line, and call print again, but this time from within the function. We now call it with the following arguments:
print([1, 2, 3], 1, 3)
This, again, will go through and look at the if statement, see that it is true, and run console.log(arr[1]). Once again, we will call print with the following arguments:
print([1, 2, 3], 2, 3)
This will then console.log(arr[2]) (the last item in the array) and again call print with the following arguments:
print([1, 2, 3], 3, 3)
however, this time, our if statement is not met / not true, as pos (3) is not less than len (3). In other words, our base case (the condition to stop the recursion) is met. So, what we do instead of printing is return.
Doing a return will take us back to where we last called our print statement, this means we will go back to inside the if statement from our previous call to print and then return again once the if statement is complete. This unravelling process continues until we return to our original call of print (outside the print function declaration). Our program then terminates after this as there is no more code to run.
printis called, if there are still letters remaining, it callsprintagain.console.log(arr[pos]); print(arr, pos + 1, len);and it will print array in reverse order. Its recursion.