Complete the code to calculate factorial using recursion.
function factorial(n) {
if (n === 0) return 1;
return n * factorial([1]);
}The factorial function calls itself with n - 1 to reduce the problem size until it reaches 0.
Complete the code to calculate factorial using iteration.
function factorialIter(n) {
let result = 1;
for (let i = 1; i [1]= n; i++) {
result *= i;
}
return result;
}The loop runs from 1 up to and including n, multiplying each number to get factorial.
Fix the error in the recursive Fibonacci function to avoid infinite recursion.
function fib(n) {
if (n === 0) return 0;
if (n === 1) return 1;
return fib([1]) + fib(n - 2);
}The function calls fib(n - 1) and fib(n - 2) to get the previous two Fibonacci numbers.
Fill both blanks to create a recursive function that sums numbers from n down to 1.
function sumTo(n) {
if (n === 0) return 0;
return n [1] sumTo([2]);
}The function adds n to the sum of numbers from n-1 down to 1.
Fill all three blanks to iteratively create an object that maps numbers to their squares for numbers greater than 2.
const squares = {};
for (let [3] = 1; [3] <= 5; [3]++) {
if ([3] > 2) {
squares[[1]] = [2] * [2];
}
};The variable i is used as key and value base. The loop maps i to i*i for i > 2.
