Can somebody explain the solution code?

Can somebody explain the code in words. I’m not understanding how this code produces the result it does, step by step. Finding recursion a little difficult to wrap my head around.

Your code so far


//Only change code below this line
function countdown(n){
if (n < 1) {
  return [];
}
else {
  var countArray = countdown(n - 1);
  countArray.unshift(n);
  return countArray;
}
}
console.log(countdown(5)); // [5, 4, 3, 2, 1]
console.log(countdown(10)); // [5, 4, 3, 2, 1]

Your browser information:

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

Challenge: Use Recursion to Create a Countdown

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.

try looking at it with this tool and see if it helps:
http://www.pythontutor.com/javascript.html

Visualization is great, but I’ll try to explain:

  1. Every recursive function starts with exit condition, similar to for or while loop, otherwise recursion will run in infinite loop:
/* return empty array if n < 1 */
if (n < 1) return [];
  1. Then a lot of functions normally define its output:
// Our result is a countdown of numbers from n - 1
// so for n = 5, we expect result to be [4, 3, 2, 1];
const result = countdown(n - 1);
  1. The last step would be just to unshift n in front of result and return result

You might ask, how JS knows that countdown(5 - 1) equals to [4, 3, 2, 1]. And the answer - it doesn’t, it just calculates it with the same logic - take 4 and put it in front of [3, 2, 1] and so on until it gets to countdown(1) where it puts 1 in front of countdown(0) that meets exit condition and stops recursion.