I want to understand this lesson

Hey, I am tying to understand this challenge but it seems unclear for me in this specific parts

first part is how the example in the lesson returns an array there are a const declared and initialized with the value of a function

and how could this constant has push and it is getting pushes in the next line it is not an array so why is that happening ?

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Recursion is a confusing subject. It has been discussed many times in this forum. This specific challenge is discussed many times, sometimes in great detail. Rather than repeat all of that, I would suggest searching for those. If there is still something that is eluding you, check back.

This is not just a brush off, this is an important part of being a developer. Developers often have to go and search to see if something has already been explained on things like Stack Overflow. This is an important skill.

1 Like

Hey @kevinSmith I have browsed the previous questions about this topic and I could not find your replies about them could you please share the link of them with me

by the way I have spend some time imagining what is happening under the hood so my question was how are we pushing to the function if it is not an array the only idea I have reached is since it reached the base case of the recursion the function returns [] so in all the recursive cases that empty array is getting pushed all the elements am I right with that

If you reread what I wrote, I wasn’t talking specifically about my replies.

I have make comments on this function here. I also make discussion here and here.

I’m sure there are others. There are also countless discussions.

Looking more closely at your question, it looks like it has nothing to do with recursion. (Sorry, I have a knee jerk reaction to the never ending flow of recursion questions.

how could this constant has push

    const countArray = countup(n - 1);
    countArray.push(n);

People misunderstand const in JS. It is saying that countArray cannot be changed. But what is countArray? It is not an array, it is a “reference type” so it is a memory address, a “reference”, that points to the place in memory. The const is saying that that memory address cannot change. But what is stored in that memory location, that can change. Yes, I know, it seems a bit odd, but that’s how JS works. For primitive types (string, number, boolean, etc.), const works the way you expect. But for reference types (objects, functions, arrays, etc.) it works like this. You can change what’s in the memory location. If you want to keep that from being changed, you have to do a freeze.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.