Complete the code to make the function call itself recursively.
function countdown(n) {
if (n <= 0) {
return;
}
console.log(n);
countdown([1]);
}The function calls itself with n - 1 to count down until it reaches zero.
Complete the code to calculate factorial using recursion.
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial([1]);
}The factorial of n is n times factorial of n-1, so the recursive call uses n - 1.
Fix the error in the recursive Fibonacci function call.
function fibonacci(n) {
if (n <= 1) {
return n;
}
return fibonacci([1]) + fibonacci(n - 2);
}The Fibonacci function calls itself with n - 1 and n - 2. The first recursive call must be n - 1.
Fill both blanks to create a recursive function that sums numbers from 1 to n.
function sumTo(n) {
if (n === 1) {
return 1;
}
return n + sumTo([1]);
}
console.log(sumTo([2]));The recursive call reduces n by 1 each time, so n - 1 is used. The function is called with 5 to sum numbers from 1 to 5.
Fill all three blanks to create a recursive function that reverses a string.
function reverseString(str) {
if (str.length === 0) {
return '';
}
return str.charAt([1]) + reverseString(str.[2]([3]));
}
console.log(reverseString('code'));The function takes the last character str.charAt(str.length - 1) and adds the reverse of the string without the last character using slice(0, str.length - 1).
