Recursion to Create a Countdown js

Tell us what’s happening:
Hello, friends,
I’m very confused, in the order given by the function [5, … , 1]
what I got by the resolution, manually, on paper is that order: [1, 2, 3, 4, 5].
I still don’t understand why the code gives this : [ 5, 4, 3, 2, 1 ] !
I have the impression that it’s reversed.
thanks

Your code so far


// Only change code below this line
function countdown(n){
if (n<1){
  return [];
}else{
  const Arr = countdown(n-1);
  Arr.unshift(n);
  return Arr;
}

}
// Only change code above this line
console.log(countdown(5))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Hi,

With a recursive function one function calls the other. The function that calls another function has not returned or exited before the function that it calls has returned or exited. So, Function one calls function two which calls function three. Function three returns its value to function two and exits first. Then function two returns its value to function one and exits. Only now the last function on the stack can exit. That’s why the values are in reversed order.

Copy this in a file, recursion.js, make another html file and use a script tag to connect to recursion.js, lauch the html file in a browser and walk through it slowly using breakpoints. (go to the debugger or the sources panel and click inside the script, a dot will appear. Refresh the page, and click on the arrows in the debugger (top right) to walk through the function) To the right you will see the ‘call stack’. Underneath you will see countdown being called five times, but the values are returned only when the fifth function has been called.

Somehow the browser remembers all the previous functions, like planes hovering in the air waiting to fly past when they are called.

Greets,
Karin

1 Like

Thank you Karin, now the idea is more clear to me.
Regards
Houcine

1 Like