Recursion with array, what am i missing?

Tell us what’s happening:
This is a weird one… I suppose I can extract the correct answer i don’t feel comfortable continuing unless I get that completely.

Although the recursion in a fractional function is understandable, or a simple countdown, when working with the array it pi**es me off that I just don’t get it.

The part which I don’t get is how an array is defined in the variable numbers in this example, through a function? It seems to me that nobody ever defined an array in this specific case/answer. So how the endNum is pushed into the array, as I don’t see any array created in the first call of the function?

function rangeOfNumbers(startNum, endNum) {
  if (endNum - startNum === 0) {
    return [startNum];
else {
  var numbers = rangeOfNumbers(startNum, endNum - 1);
  return numbers;

What am I missing?

  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.3 Safari/605.1.15.

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

it’s not the first function call that creates an array, it’s the last one

in recursion you have a function (1) calling an other function (2) calling an other function (3) … calling an other function (N)
each of these functions will not complete until the following ones are completed. So, at one point the series reach the base case with the Nth, and the others start resolving
N gets an output, which is passed to N - 1, so N-1 gets an output, which is […] passed to 3, and also 3 uses that received value to compute and create its own output, which is passed to 2 that now can finally finish computing and create its own output, which is passed to 1, which can also finally compute its output, and return a value

Hey, thank you very much for your reply. So I suppose this should work also:

Let’s say we have a countDownToArray function which stores all the numbers until it hits 0 into an array. The Chrome Developer Console returns an error: “cdToArray is not defined”.

function countDownToArray(n) {
    if (n <= 0) { 
    return [n] }
 else {
var cdToArray = countDownToArray(n-1);
return cdToArray   }

you may want to avoid spelling mistakes when you try those things

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Oh my… My brain is fried! Thank you again ieahleen! At least now I understand the solution in this specific challenge!

1 Like

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