1

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 ?

2
  • 1
    It's fully synchronous. It's just executing the recursion before continuing. Commented 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 --- 1 Commented Jan 2, 2020 at 8:44

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.