• Post author:
• Post category:Blog

## 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: The function test is defined, which takes a parameter named counter. Inside the function, the string “test” is printed to the console using console.log(“test”). Next, there is an if statement that checks if the counter variable is greater than 0. 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. The recursive call in step 4 continues until the counter becomes 0. 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: The initial call to test(3) is made. Inside test(3), “test” is printed to the console. The counter is decremented to 2, and a recursive call test(2) is made. Inside test(2), “test” is printed to the console. The counter is decremented to 1, and a recursive call test(1) is made. Inside test(1), “test” is printed to the console. The counter is decremented to 0, and a recursive call test(0) is made. Inside test(0), “test” is printed to the console. Since the counter is now 0, the recursive calls stop. The execution of the function completes. Therefore, the word “test” will be displayed in the console four times.

Subscribe
Notify of