Now, having entered the function, we have i, so it returns itself with the parameter i-1 (4) and concats i (5).
No, he is not coming back. What he does is the call itself, which is recursion, then it returns the result of that call with the last element connected.
So range1(5) will call range1(4) , which will call range1(3) , etc. When it reaches zero, it will stop making calls and just return an empty array.
range1(0) returns [] , so range1(1) returns [].concat(1) , which is [1] , then range1(2) returns [1].concat(2) , which is [1,2] , etc. When we return to range1(5) it returns [1,2,3,4].concat(5) , which is [1,2,3,4,5] .
Note. This function works well for creating small arrays, but if you need a large array, it will be much faster to just create an array and fill it with a regular loop.
Guffa source share