I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
Remember, you will not execute the second line until you have reached the base case. So when you finally execute the second line for the first time what will arr equal? I’d suggest you add some more console logs, such as a console log of arr right at the beginning of the function, and perhaps another one of arr between the first and second lines above.
Personally, I think this is a bad example to teach recursion and so I can understand why you are having a hard time with it as nobody would naturally think to use recursion to solve this problem. Go ahead and try to understand what is going on here just for curiosity’s sake and then promptly forget you ever saw this solution.
Yeah. I immediately recognized that it was a bad way to use recursion. I actually solved it by using sort and then returning the array length minus 1 . But I’m practicing recursion so I was just trying to understand how this way works.
now I can understand that ‘res’ slices the array until it meets the if statement so its
var ret = 2>= 12
so that comes out to false, But if the slice removed everything from the array up to 2 then how does res ever end up being 99 in the ret variable?
Yes, each recursive call to findHighest does remove another element from the beginning of the array, but then once you reach the base case you have to unroll the recursion and thus you basically start adding those elements back in to the array as you work your way backwards through the recursion.
Again, I would recommend you add some console logs as I suggested above so you can see this in action.
yes. I did console log pretty much each step of it. I saw that it starting adding them back I just don’t know which part of the code instructed it to do so or even how it would access those numbers again if they were sliced off. I know that slice doesn’t mutate the original array. but res isn’t the original and only had 2 left so how do the others reappear?