Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a function that calls itself.
Javascript
function recurse() {
console.log('Hello');
[1]();
}
recurse(); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using console or log instead of the function name.
Trying to call a method that doesn't exist.
✗ Incorrect
The function calls itself by its name recurse(), which is how recursion works.
2fill in blank
mediumComplete the code to add a base case that stops recursion when n is 0.
Javascript
function countdown(n) {
if (n [1] 0) {
return;
}
console.log(n);
countdown(n - 1);
}
countdown(3); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using > or < instead of ==, which leads to incorrect output.
Using != which does not stop at zero.
✗ Incorrect
The base case checks if n == 0 to stop the recursion.
3fill in blank
hardFix the error in the recursive function to avoid infinite recursion.
Javascript
function sum(n) { if (n <= 0) { return 0; } return n + sum([1]); } console.log(sum(3));
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Adding 1 to n causes infinite recursion.
Passing n unchanged causes infinite recursion.
✗ Incorrect
To reduce n each time and reach the base case, we call sum(n - 1).
4fill in blank
hardFill both blanks to create a recursive factorial function with a base case.
Javascript
function factorial(n) {
if (n [1] 1) {
return 1;
}
return n * factorial([2]);
}
console.log(factorial(4)); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using == in base case but not handling n=0 properly.
Using -1 instead of n - 1 in recursive call.
✗ Incorrect
The base case stops when n is less or equal to 1, and the recursive call uses n - 1.
5fill in blank
hardFill all three blanks to create a recursive function that counts down and stops at zero.
Javascript
function countDown(n) {
if (n [1] 0) {
return;
}
console.log([2]);
countDown([3]);
}
countDown(3); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of > in base case returns immediately without printing numbers.
Printing n - 1 instead of n.
Calling countDown with n instead of n - 1.
✗ Incorrect
The base case checks if n is greater than zero, prints n, then calls countDown with n - 1.