• Post author:
  • Post category:Blog
  • Reading time:3 mins read
  • Post last modified:June 12, 2024

Analyze the code below:

function test(counter) {
    console.log("test");
    if (counter > 0)
     test(--counter);
}
test(3);

How many times will the word “test” be displayed in the console?

  • 0
  • 2
  • 4
  • 3
  • Explanation & Hint:

    The code snippet will display the word “test” four times in the console. Let’s go through the code step by step:

    1. The function test is defined, which takes a parameter named counter.
    2. Inside the function, the string “test” is printed to the console using console.log(“test”).
    3. Next, there is an if statement that checks if the counter variable is greater than 0.
    4. If the counter is greater than 0, the test function is called recursively with the counter decremented by 1 (–counter). This recursive call repeats the execution of the function.
    5. The recursive call in step 4 continues until the counter becomes 0.
    6. When the counter reaches 0, the recursive calls stop, and the function execution completes.

    Now, let’s analyze how many times the word “test” will be displayed in the console based on the code:

    1. The initial call to test(3) is made.
    2. Inside test(3), “test” is printed to the console.
    3. The counter is decremented to 2, and a recursive call test(2) is made.
    4. Inside test(2), “test” is printed to the console.
    5. The counter is decremented to 1, and a recursive call test(1) is made.
    6. Inside test(1), “test” is printed to the console.
    7. The counter is decremented to 0, and a recursive call test(0) is made.
    8. Inside test(0), “test” is printed to the console.
    9. Since the counter is now 0, the recursive calls stop.
    10. The execution of the function completes.

    Therefore, the word “test” will be displayed in the console four times.

For more Questions and Answers:

JavaScript Essentials 1 | JSE1 – Module 5 Test Exam Answers Full Score 100%

Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments