Can someone explain the output logic on this code?

function rangeOfNumbers(startNum, endNum) {
  if (endNum - startNum === 0) {
    return [startNum];
  } else {
    var numbers = rangeOfNumbers(startNum, endNum - 1);
    return numbers;
console.log(rangeOfNumbers(15, 20))

Here is the console output:

(2) [15, 16]
(3) [15, 16, 17]
(4) [15, 16, 17, 18]
(5) [15, 16, 17, 18, 19]
(6) [15, 16, 17, 18, 19, 20]
(6) [15, 16, 17, 18, 19, 20]

Why does the first pass put two numbers in the array? I was expecting to see one number each pass.

Also… the function is adding endNum into the array each time… yet the numbers are assigned to the array from the lowest number to the highest number passed into the function. Why is that the case?

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 (’).

Because you are console logging after pushing a number into the array.

Ahh fixed that to see what is going on… thanks!

If anyone can help me see the logic on my second question I would greatly appreciate!

You’re calling the function recursively with a smaller value of endNum (side note, let should be used instead of var. const works even better here)

but as the function gets called in order of the loop endNum is decreasing i.e. 20, 19, 18, 17 etc… Yet, the function is adding numbers into the array as 15, 16, 17 ,18 etc… If this is correct I do not understand how that is happening within the context of recursion, and if that is now how this recursive function works I do not understand what I am not seeing.

There is no loop. Forget about loops.

When you call a function, the code below it does not run until the function call finishes. Tme call with endNum-1 must finish and return before the push(endNum) happens.

Got it. This is a huge help here.

1 Like

That’s one of the things about recursion that takes a while to remember. Each function call is separate.

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