function test(param, n) {
console.log(param, "start --- ", n);
if (n > 1) {
console.log(param, "before first recursion --- ", n);
test("test-1", n - 1);
console.log(param, "after first recursion --- ", n);
test("test-2", n - 1);
console.log(param, "after second recursion --- ", n);
}
console.log(param, "end --- ", n);
}
test("initialize", 3);
In output console
test-1 after first recursion --- I am getting value 2, can someone please explain the flow of code is going as, I was expecting 3 as the output, because in my understanding if the test("test-1", n-1) is completed then the next call i.e. test("test-2", n-1) will be getting 3 value as fresh input, also is the js working synchronous here ?
-
1It's fully synchronous. It's just executing the recursion before continuing.VLAZ– VLAZ2020年01月02日 08:40:20 +00:00Commented Jan 2, 2020 at 8:40
-
Your output should be: initialize start --- 3, initialize, before first recursion --- 3, test-1 start --- 2, test-1 before first recursion --- 2, test-1 after first recursion --- 2, test-2 start --- 1, test-2, end --- 1SPlatten– SPlatten2020年01月02日 08:44:14 +00:00Commented Jan 2, 2020 at 8:44
1 Answer 1
You could use some indentations to the output and look which level is actually running.
function test(param, n, level = 0) {
console.log(''.padStart(level * 2), level, param, "start --- ", n);
if (n > 1) {
test("test-1", n - 1, level + 1);
test("test-2", n - 1, level + 1);
}
console.log(''.padStart(level * 2), level, param, "end --- ", n);
}
test("initialize", 3);
VLAZ
29.6k9 gold badges65 silver badges88 bronze badges
answered Jan 2, 2020 at 8:43
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js