The Prompt for the recursion problem is: Get the length of an array using recursion without accessing its length property.
Here is what I have come up with:
function getLength(array, count = 0) {
array.pop();
let newCount = count + 1;
if (array = []) return newCount
let newArray = array
return getLength(newArray, newCount)
}
// To check if you've completed the challenge, uncomment these console.logs!
console.log(getLength([1])); // -> 1
console.log(getLength([1, 2])); // -> 2
console.log(getLength([1, 2, 3, 4, 5])); // -> 5
console.log(getLength([])); // -> 0
The Strategy was to keep incrementing count as long as there was still elements after the array was "popped"
So:
if the input for array was [2,4,3,5]
I figured my code would initially:
- pop one element from the input array making array = [4,3,5]
- declare a new variable "newCount" = 1
- then check and see if the array was empty, and it should still contain 3 elements
- So, it would then rerun the function with the newArray as the "array" and newCount as 1. To eventually increment newCount to 2 and so on...
Once the array is finally empty it should return the count which should be equal to the length (I think)
HOWEVER
My IF statement keeps returning true when its evaluated, and in the chrome console I can't figure out why array just completely empties in the IF statement.
In other words, my solution keeps returning 1 over and over and over. When even in the console everything seems to be running smoothly (the array has been popped appropriately) until it reaches the IF statement and it just empties and returns count = 1.
If someone could please explain why this would happen that'd be great, thank you in advance!