I want to know that the following code is return number from 10 to 1 but after doing that it calls itself again 10 times but not doing anything. I tried to understand the code step by step with the help of the debugger variable but was not able to.
let countDown = function f(fromNumber) {
console.log(fromNumber);
let nextNumber = fromNumber - 1;
if (nextNumber > 0) {
f(nextNumber);
}
}
let newYearCountDown = countDown;
countDown = null;
newYearCountDown(10);
For more reference, please visit Javascripttutorial to know more about the code.
Recursion is a process of calling itself. A function that calls itself is called a recursive function. In your example, your first function doesn't get completed, but it's if condition is what is being run. During the if condition, your function is more like put on hold as another call is made. Your first function waits for it to complete.
In this fashion, 10 function calls are made and all are waiting inside the if condition. After the last condition (nextNumber == 0) fails, the function returns back to the 9th function where the if condition was waiting. Similarly, all your functions will get completed one by one from 9 to 1.