Hi,
I’ve watched several videos on recursion and feel like I have an okay grasp on it. However I do have some questions about this code I’ve been studying. Pretty simple, just return the highest integer in the array.
function findHighest(arr){
if (arr.length==1)
{
return arr[0];
}
else
{
var res = findHighest(arr.slice(1));
var ret= res>=arr[0]? res:arr[0];
return ret;
}
}
So… I understand the if
portion of it. But confused on the else
part. What does the slice function have to do with the array? I thought all slice(1) would do is cut out arr[0] and return everything from arr[1]…arr[n]. What exactly is calculated when it says res >= arr[0]
?
Thanks!
I’m still not sure to be honest.
For example if we are given [1,2,3,4]
It would skip the if statement since arr.length > 1 and execute the else part. This would then call the function findHighest(arr.slice(1)) which would slice the array into [2,3,4].
The part I don’t get is the variable ret, which would be
[2,3,4] >= 1
. How would I know if this is true or not? Is it based off the length of the array or is there a value I should be looking for?
Is it going to test every element of the array ? That’s the only thing I can think of right now.
function findHighest(arr){
if (arr.length == 1) {
return arr[0];
} else {
var res = findHighest(arr.slice(1)); // What is res, in words?
var ret = res >= arr[0] ? res : arr[0]; // What does this simpler version of the code do: var big = a >= b ? a : b
return ret;
}
}
I added a couple of comments.
I’m not sure why you think that res >= arr[0]
means [2, 3, 4] >= 1
. What is res
? What will findHighest(arr.slice(1))
return?
Isn’t res
just a variable that contains another function?
I always thought slice
just returns an array from a start index to an end index.
So arr.slice[1]
would return the arr
starting from the 2nd element until the end.
Is that wrong?
And for var big = a >= b ? a : b
It is asking if a
is greater than or equal to b
then return a
and if it is false return b
res
holds the result of calling the function on a slice of the original array. It does not hold a slice.
In that case… I think it would keep calling the function findHighest until it meets the if condition.
I’ll keep watching videos/reading online and try to learn more.