Hello! After searching google, posting in the forum and reviewing the reply, and reading this thread, still don’t understand the example code. As usually happens when I am having difficulty understanding, read-search-ask only leads to more confusion.
Below is my question and a forum reply, with my comments/questions. I would appreciate any help. Thanks!
can anyone please explain what is happening in the example code (especially after the ‘else’). I do not understand the code even after reading (several times) the explanation provided. In the forum I see a lot of references for how to write the correct solution code but I don’t understand the example code so I’m unable to figure out where to start with the solution. Thank you.
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]
Reply
first think of ‘n’ as 5.
if n is less than 1 then return an array,
else (if the n is greater or equal 1) get the return value of countup(5-1) and push to that value n (which is 5).
what is the value of countup(5-1) in other words countup(4) ?
‘n’ in this context is 4.
if n is less than 1 it return an array,
else (if the n is greater or equal to 1) get the value of countup(4-1) and push to that value ‘n’ ( which is 4).
a question for you.
what is the value of countup(4-1) ?
SolutionReply
Thank you for your response.
first think of ‘n’ as 5. Ok, I understand this
if n is less than 1 then return an array, yes I understand this
else (if the n is greater or equal 1) get the return value of countup(5-1) and push to that value n (which is 5). what is the return value of ‘countup(5-1)’?
what is the value of countup(5-1) in other words countup(4) ?
‘n’ in this context is 4. how does n become 4? n-1 is 4, but how does n become 4? How can n be the same as n-1?
if n is less than 1 it return an array,
else (if the n is greater or equal to 1) get the value of countup(4-1) and push to that value ‘n’ ( which is 4). Again, I don’t understand how the value of n has changed. we called the function with ‘5’ so how can it now be 4? n-1 is 4, but ‘n’ itself is still 5, right?
a question for you.
what is the value of countup(4-1) ? this would be countup(3)
Also - I think .push is used to add to the end of an array, but where are we actually creating the array to add to?