Recursion in Javascript
Question 1: Sum all numbers
Write a function called sumRange
. It will take a number and return the sum of all numbers from 1 up to the number passed in.
Sample: sumRange(3) returns 6, since 1 + 2 + 3 = 6.
let count = 1; let data = 0; function sumRange(number){ if(count > number){ console.log(data); return; } data+=count; count++; sumRange(number);
}
sumRange(4);
Question 2: Power function
Write a function called power
which takes in a base and an exponent. If the exponent is 0, return 1.
let count = 1;
let data = 1;
function power(base,exponent)
{ if(exponent==0){ console.log(base); return; }
if(count > exponent){ console.log(data); return; } data *= base; count++; power(base,exponent);
}
power(2,4);
Question 3: Calculate factorial
Write a function that returns the factorial
of a number. As a quick refresher, a factorial of a number is the result of that number multiplied by the number before it, and the number before that number, and so on, until you reach 1. The factorial of 1 is just 1.
let count = 1;
let data = 1;
function factorial(number){ if(count > number)
{ console.log(data);
return;
}
data *= count;
count++;
factorial(number);
}
factorial(4);