Reputation: 41
I thought the following code will never reach to the console.log
lines, because the next()
function already run before to reach to the console.log
lines and the if else
condition with return
prevent it too, but it is not so. Why?
var arr = ['a', 'b', 'c'];
var i = 0;
function next() {
if (i < arr.length) {
next(i++);
console.log('why go here 1:' + i); // 3,3,3
} else {
return;
}
console.log('why go here 2:' + i); // 3,3,3
}
next();
Upvotes: 3
Views: 132
Reputation: 92461
Each of those calls to next()
will return once the edge condition is met (in this case once i
is larger than arr.length
). This is the part of recursion that's usually called "unwinding" — each recursive call returns as the calls it called return. So once the next()
function returns it continues on to the console.log()
You can adjust your code so it logs when the function starts and returns with a count to visualize the recursion:
var arr = ['a', 'b', 'c'];
let i = 0;
let space = 1
function next() {
let s = space++
console.log(" ".repeat(s) + `next ${s} called`)
if (i < arr.length) {
next(i++);
} else {
console.log("edge condition -- finally start unwinding")
console.log(" ".repeat(s) + `next ${s} retured from edge condition`)
return;
}
console.log(" ".repeat(s) + `next ${s} retured`)
}
next();
Here you can see the four next()
functions called without returning, but once you hit the edge condition, they unwind and return in the opposite order.
Upvotes: 4
Reputation: 1395
The if
statement/function will run everything in the scope unless there's something such as a break
to terminate the current loop, switch, or label statement.
Upvotes: 0
Reputation: 10258
You need to step through it with a debugger or pen/paper to understand the flow completely.
When next(i++)
returns, like after any function call, it will go to the next line. If you want the code to stop, you have to return
after calling next(i++)
. Ex: return next(i++);
or next(i++); return;
Upvotes: 0