This post was originally published on Tech.io. Their platform provides runnable code snippets so you can run the answer code live in the browser!
Recursion in Javascript
This post goes through code samples utilizing recursion. We will state the problems and then provide runnable code snippets that show the answer. The answers will be hidden you can try them on your own and then peek.
Answer 1
The most important thing we need for recursive solutions is a base case. There needs to be a way of exiting the loop or the function will go on forever. The base case in the below code code is that when the input is 1, return 1. Eventually the function will return 6, the correct answer
Once you understand this code move on to the next problem
1
2
3
4
5
6
7
8
var output = sumRange(3)
console.log(output);
functionsumRange(num){
if(num == 1) return1;
return num + sumRange(num - 1);
}
Question 2: Power function
Write a function called power which takes in a base and an exponent. If
the exponent is 0, return 1.
Sample:
1
2
3
4
5
console.log(power(2, 4)); // 16
console.log(power(2, 3)); // 8
console.log(power(2, 2)); // 4
console.log(power(2, 1)); // 2
console.log(power(2, 0)); // 1
Answer 2
You can think of it in terms of this example:
1
2
3
4
2^4 = 2 * 2^3;
2^3 = 2 * 2^2;
2^2 = 2 * 2^1;
2^1 = 2 * 2^0; // once our exponent is 0 we KNOW that the value is always 1!
1
2
3
4
5
6
7
8
9
10
console.log(power(2, 4)); // 16
console.log(power(2, 3)); // 8
console.log(power(2, 2)); // 4
console.log(power(2, 1)); // 2
console.log(power(2, 0)); // 1
function power(base, exponent){
if(exponent == 0) return 1;
return base * power(base, exponent - 1);
}
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.
Write a function called all which accepts an array and a callback and returns
true if every value in the array returns true when passed as parameter to the
callback function
Sample:
1
2
3
4
5
var allAreLessThanSeven = all([1,2,9], function(num){
return num < 7;
});
console.log(allAreLessThanSeven); // false
Answer 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var allAreLessThanSeven = all([1,2,9], function(num){
The function should return an array containing repetitions of the number argument.
For instance, replicate(3, 5) should return [5,5,5].
If the times argument is negative, return an empty array.