Forum Moderators: open
var hanoi = function (disc, src, aux, dst) {
if (disc > 0) {
hanoi(disc - 1, src, dst, aux);
document.writeln('Move disc ' + disc +
' from ' + src + ' to ' + dst);
hanoi(disc - 1, aux, src, dst);
}
}hanoi(3, 'Src', 'Aux', 'Dst');
initial entry disc = 3
-- pre entry disc = 2
---- pre entry disc = 1
---- writeln disc = 1
---- exit disc = 1
-- writeln disc = 2
---- post entry disc = 1
---- writeln disc = 1
---- exit disc = 1
-- exit disc = 2
writeln disc = 3
-- post entry disc = 2
---- pre entry disc = 1
---- writeln disc = 1
---- exit disc = 1
-- writeln disc = 2
---- post entry disc = 1
---- writeln disc = 1
---- exit disc = 1
-- exit disc = 2
exit disc = 3
function foo() {
bar();
alert('hello');
} Then when foo is called, it will execute bar and then alert 'hello'. It does not stop processing because it called another function. Your example is identical, except that the function it calls happens to be the same function currently executing. The result is that you end up recursing and then walking back down the tree when you're done.
my question is how can it ever get to the second call of the if statement inside the curly braces since if it passes the if test the function will call itself again before it ever reaches the second call in the if statement
There is nothing special about a function calling itself.
When the first call completes the writeln and second call will happen.