I’m a beginner in Javascript. And while trying recursion by myself, i got some strange result using while loop. And just the right result using If statement.
Here’s the code and the result :
var test = function f(n){
while(n > 0){
document.write(n);
f(--n);
}
};
test(5);
And the result :
5432112113211211432112113211211
While using If statement
var test = function f(n){
if(n > 0){
document.write(n);
f(--n);
}
};
test(5);
The result is :
54321
I can’t really debug it in the while case. It gets me confused at some point to be honest.
The important thing to note is that every time you run the code inside of
f, a new scope is created with a new variable calledn. So, by recursively callingf, you are adding to scope chain. You keep adding to the scope chain untiln > 0isfalse. Once it is false, you start traversing back up the scope chain, where other versions ofnexist. The process repeats until allnvariables in all of the scopes become0.Notice the pattern that occurs when I add some spaces to your numbers below. I’ve added a space every time the code has to go up the scope chain. Every set of numbers represents the code going down the scope chain.
54321 1 21 1 321 1 21 1 4321 1 21 1 321 1 21 1
Here is a jsfiddle that should be helpful. It prints two numbers: the first one represents which scope you are in and the second one is the same number that you were printing in your code. Look at the first numbers and try to wrap your head around how a new number is created for each scope. Try to think about what the value of
nshould be when you return to that scope later in the program.