0

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:

  1. pop one element from the input array making array = [4,3,5]
  2. declare a new variable "newCount" = 1
  3. then check and see if the array was empty, and it should still contain 3 elements
  4. 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!

Philip
  • 1
  • 2
  • 3
    `if (array = [])` is ***assignment***, not equality check. Moreover, equality check would be wrong - [Why doesn't equality check work with arrays](https://stackoverflow.com/q/30820611) – VLAZ May 20 '22 at 05:16
  • [You can simplify the code a little](https://jsfiddle.net/0k7c3nx8/1/). Run the check first and if there's no element at the first index return the count otherwise call the function again with the array and an updated count. No need for extra variables either. – Andy May 20 '22 at 05:31

0 Answers0