Hello! I was going through Basic JavaScript - Replace Loops using Recursion, and couldn’t understand the base case of the example (multiply function).
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
I get how and why it works when n > 0. But if I call this function with n as 0,
multiply(arr, 0);
It will return 1. Isn’t it simply wrong? Shouldn’t it return a string of error message or something?
Or is it possible to do this
if (n <=0) {
return "Wrong input";
}
and set base case differently?
Thanks in advance!
You want it to return 1 because the function calls itself with (n - 1). If I call the function with 1, then the function multiplies the array by 1, moves to 0, and returns 1.
So, let’s do multiply([1, 2], 2)
.
First it returns multiply([1, 2], 2 -1) * arr [2-1]
, or multiply([1, 2], 1) * arr[1]
.
Now it’s calling the function again. We look at that, and we get:
multiply([1, 2], 0) * arr [1-1] * arr[2-1)
Finally, it calls the function with 0
. Now, if we use your suggested base case of returning “wrong input”, we get:
"wrong input" * arr[0] * arr[1]
, which evaluates to NaN.
If we use the suggested base case of return 1
, then we get 1 * arr[0] * arr[1]
, which yields the expected result of 2
.
Does this make sense?
1 Like
you would need to separate the recursion base case, where you need the 1
, or arr[0]
as starting value, and the invalid input thing, otherwise you would find yourself with "Wrong input" * 5
(or any other number) and that results in NaN
when the recursion is using a function call with a lower n
to calculate the current call
2 Likes
Thanks for the detailed explanation @nhcarrigan, @ilenia, I will try writing different base case!
1 Like