Reputation: 6481
So I was going through the code for mergesort, which uses recursion. I am a bit confused about how the code works. Since the confusion is regarding recursion, I am placing similar code below, which is much simplified and focuses just on the recursion part:
var index = 0;
function parent() {
console.log("parent called");
if(index < 5) {
index++;
return child(parent());
}
else return 1;
}
function child() {
console.log("child called");
}
parent();
Above code outputs:
"parent called"
"parent called"
"parent called"
"parent called"
"parent called"
"parent called"
"child called"
"child called"
"child called"
"child called"
"child called"
I was expecting a "child called" after each "parent called", since parent
calls child
each time unless index
becomes more than or equal to 5. So after the first call to parent
, parent
calls child
, which then calls parent
, and so on. So why is the output showing five successive "parent called" and then five successive "child called"?
I tried to understand it with a visualizer for call stack in JS, but I still didn't understand why child
just puts the parent
in stack, but itself is not executed at that time? You can see it in action here.
Upvotes: 0
Views: 122
Reputation: 943671
child(parent());
parent
has to be called and finished before it returns a value that can be passed to child
.
So the first parent
is called, it gets to the second child(parent())
link and recursively calls the second parent
which gets to the third child(parent())
and so on until something returns 1
and that can be passed to child
.
Upvotes: 1
Reputation: 64657
When you do:
child(parent());
It has to execute parent()
to know what value to send to child
. So it keeps calling parent
until it gets to the else return 1;
, then keeps passing the return value to child
Upvotes: 1