The confusion:
I inserted console log to the example provided by @snigo to see if i will understand what exactly is happening. when i saw this values stored in the array [3,2,1] i ve been wondering from where 3 popped up. Right after when [2,1] is stored in the array, 3 is added to it immediately. how? from where 3 came from? part of console log results
5
[ 5 ]
4
[ 4 ]
3
[ 3 ]
2
[ 2 ]
[ 2, 1 ] [ 3, 2, 1 ](this line is in Question)
Your code so far
function countdown(n) {
// base case
if (n === 1) return [1];
const output = [n]; // [2]
console.log(n);
console.log(output);
console.log(output.concat(countdown(n - 1)));
return output.concat(countdown(n - 1)); // [2, 1]
}
console.log(countdown(5));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36.
I am a beginner as well and when I first learned recursion I was confused too. Recursion is often described as a function that calls itself. So, to a beginner it might seem like it just magically works. But there is actually something going on that isn’t magic.
Recursion finally clicked for me during Harvard’s CS50 course. Doug LLoyd’s explanation of recursion and call stacks with visuals are what made it finally stick for me. I would share Doug’s video but the code is written in C.
Colt Steele has great videos on recursion and call stacks that are written using Javascript so I will share those videos instead.
then the function with n=3 keeps executing
in that one an array with value of [3] is initialized, and is concatenated to the return value of the function with n=2
Thanks, @ILM.
Thats the information that i was lacking.
The video shared by @jwilkins.oboe helped a lot.
And thanks to the link for visualizing javascript log