JS uses some abstractions, stack
(LIFO) and nested function calls
:
When a function makes a nested call, the following happens:
The current function is paused.
The execution context associated with it is remembered in a special data structure called execution context stack.
The nested call executes.
After it ends, the old execution context is retrieved from the stack, and the outer function is resumed from where it stopped.
I wrote a short faq
about recursion (is not the same exercise but I think is similar enough):
code
function rangeOfNumbers(startNum, endNum) {
if(startNum === endNum) {
return [endNum];
} else {
let arr = rangeOfNumbers(startNum + 1, endNum);
arr.push(startNum);
return arr;
}
}
let result = rangeOfNumbers(1,4);
console.log(result);
// [ 4, 3, 2, 1 ]
1.- What happens when the base case is evaluated as false?
The function calls itself:
Steps: 4,6,8
2.- What happens when the base case is evaluated as true?
Returns an array:
Step: 10
3.- The Array, where does it come from?
From the base case:
Step: 10
4.- Why can I push startNum to arr?
Because after the base case is evaluated as true, arr is an array:
Step: 11
5.- Why I’m Getting [4,3,2,1] ?
Because JavaScript uses a “stack” (LIFO, last in first out):
Steps: 10, 13, 16, 19
6.- How can I get [1,2,3,4]?
Replace push
with unshift
function rangeOfNumbers(startNum, endNum) {
if(startNum === endNum) {
return [endNum];
} else {
let arr = rangeOfNumbers(startNum + 1, endNum);
arr.unshift(startNum); // <- here
return arr;
}
}
let result = rangeOfNumbers(1,4);
console.log(result);
// [ 1, 2, 3, 4 ]
7.- Related topics:
- nested (function) calls
- call stack
Cheers and happy coding
Notes:
- If you know spanish, I recorded a video explaining recursion step by step:
- I also wrote a blog post (it has 27 images)
https://diegoperezm.github.io/blog/recursion.html