function count(n) {
if (n === 1) {
return [1];
} else {
var numbers = count(n - 1);
numbers.push(n);
return numbers;
}
}
If you call function count(5) it gives 1,2,3,4,5. However somethings are unclear in the count function. (1) Var numbers is never declared as an array so i don’t know why we are able to push into it like an array. (2) I expect the n-1 that first run to be 4, so i expect the end result to be something like 4,3,2 and not 1,2,3,4,5.
the first value returned is an array because when the following is reached then the function doesn’t call itself anymore but return a value.
The second to last function call has a value for its numbers variable, which is an array (as that is what count(1) has returned). So now n which in this iteration is 2 is pushed, the array is returned and count(2) has an output, and so on till the process reaches the first function call
This is where a console message within a function can be very informative about what is going on. Try putting console.table(numbers) just before the function returns numbers;.
count(3);
n = 3;
n === 1? false // return [1] skipped.
// Here count is called again, hence this steps is paused.
var numbers = count(n - 1); // n would be 2
# STEP1
n = 2;
n === 1? false // return [1] skipped.
// Here count is called again, hence this steps is paused.
var numbers = count(n - 1); // n would be 1
// Here the function is paused while the count(n-1) is executed
#STEP2
n = 1;
n === 1? true // an array with one is returned.
// Now the function call retraces its steps (yep, backwards now)
#Continue with STEP2
// Remember, n = 2
numbers = [1];
numbers.push(2);
return [1, 2];
#Continue with STEP1
// Remember, n = 3
numbers = [1, 2];
numbers.push(3);
return [1, 2, 3];
It helps me understand some algorithms, I hope it helps You too .