When a block (something that starts with {
and contains statements) is entered into, a new "variable environment" is created. You could think of this as something that maps each identifier for that block execution to its value.
Each time a function is called, a new such environment is created.
In this case, the parameters startNum
and endNum
are stored in an environment the first time the function is called. Then, when the interpreter runs across
rangeOfNumbers(startNum, endNum - 1).concat(endNum);
The currently running function (the one linked to the environment just described) gets suspended, and a new function is put onto the call stack, creating another environment. The process repeats itself until the end of the recursive logic is reached and [startNum]
is returned (or the stack is blown). At that point, you have a bunch of rangeOfNumbers
functions in progress, each with their own environments. At that point, you could imagine it as something like
rangeOfNumbers { startNum: 3, endNum: 5 } (this is the intial call; currently suspended)
rangeOfNumbers { startNum: 4, endNum: 5 } (currently suspended)
rangeOfNumbers { startNum: 5, endNum: 5 } (executing, about to return)
The innermost function returns its [startNum]
and terminates, and so the last function resumes, now with the useable return value:
: rangeOfNumbers(startNum, endNum - 1).concat(endNum);
gets evaluated to, when the endNum
is 5:
: [5].concat(endNum);
The process continues up the stack until all of the recursive calls are finished, and you just have the initial
rangeOfNumbers { startNum: 3, endNum: 5 }
which then finishes itself.
So, while the recursive calls are going on, the values from the prior calls are stored in each of those calls' environments.
If I'm not mistaken, concat merges two or more arrays, but there are no arrays.
[startNum]
is an array returned at the innermost point of recursion. concat
can also create a new array by taking one array as an argument, and the value to append as another. For example, [5].concat(4)
evaluates to [5, 4]
.