Hi guys! I almost finish the JS course, but I am stuck here
This is the code:
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1); // HERE! HELP! I don't get it when it says: countup(n - 1) , okay, it uses the function, but it should be decreasing then, not increasing//
countArray.push(n);
return countArray;
}
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]
At first, this seems counterintuitive since the value of ndecreases , but the values in the final array are increasing . This happens because the push happens last, after the recursive call has returned. At the point where n is pushed into the array, countup(n - 1) has already been evaluated and returned [1, 2, ..., n - 1] . I do not get this part, could you please give me another example? I would appreciate it a lot!
Also this is the lesson. I have to submit a solution to the opposite type, when it is truly incrising, as I do no it get it, I am not able to move forward. Thanks in advance!
That’s exactly my question. The lesson affirms: At first, this seems counterintuitive since the value of ndecreases , but the values in the final array are increasing . This happens because the push happens last, after the recursive call has returned. At the point where n is pushed into the array, countup(n - 1) has already been evaluated and returned [1, 2, ..., n - 1] ., but I don’t get it
Push added an element to the end of the array. Each function call gets completed in order.
Your countup(5) returns the result of countup(4) with 5push ed onto it, or [1, 2, 3, 4, 5]. This means that countup(4) must be called and finish returning before countup(5) pushes 5 and returns the array.
@JeremyLT I wholeheartedly appreciate your support. Please: Take a look, I am sure I can bypass this if I undertstand the following issue:
Let’s suppose this is my code:
function countdown(n) {
if (n < 1) {
return ;
} else {
const arr = countdown(n - 1);
arr.unshift(n);
return arr;
}
}
console.log(countdown(2));
OK. The function begins with 2.
function countdown(2) {
if (2 < 1) {
return ;
} else {
const arr = countdown(2 - 1); //Now it is remaning “1” one! Fine…
arr.unshift(2);
return arr;
}
}
It addes number “2” to a new array, which it is: [2].
Now:
function countdown(1) {
if (1 < 1) {
return ;
} else {
const arr = countdown(1 - 1); //Now it is remaning “0”, we are done, fin!
arr.unshift(1);
return arr;
}
}
I already have [2], and as it calls unshift function, which means it addes a new value at the beginning, so we now have: [1,2]. The console gives me: [2,1] :/, it’s quite the opposite! please