Reversed
What happens if you reverse the statements in printList
?
Well, now the function is being called before printing the value of i
. So the values are printed during the "unwind recursion" phase, after the base case is invoked. This would print the values in reverse (in other words, 5, 4, 3, 2, 1
).
xxxxxxxxxx
11
function printList(i) {
// base case
if (i > 5) {
return; // do nothing
}
// recursive case
printList(i + 1);
console.log(i);
}
​
printList(1);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment