Help with recursion - capitalizeFirst

Hi Guys,

I going thru this solution where it is meant to capitalize first letter of each word in given set of arrays.

But I unable to understand how this made to recursively call for third time. For example if we give an array of length three, then it should be able to recurse only twice because of the third time we not going over iteratively.

Step 1: array will not length of 1 and hence we go first call capitalizeFirst which will take the first element and return the res

Step 2: We take the second element and transform it to string and push it and that’s it we returning !!!

I;m not sure how it goes to next value or in our case last value of the array :sweat_smile: Please help me understand thi :slight_smile:

function capitalizeFirst (array) {
  if (array.length === 1) {
    return [array[0][0].toUpperCase() + array[0].substr(1)];
  const res = capitalizeFirst(array.slice(0, -1));
  const string = array.slice(array.length - 1)[0][0].toUpperCase() + array.slice(array.length-1)[0].substr(1);
  return res;

try looking at how the code execute with this tool and see if you can follow what’s going on. Remember that you need a function call to see a function executing!

1 Like

Thanks for your help :slight_smile: I did use debugger and step-in to the code to see how its calling for third time but still couldn’t figure it out :frowning:

If you could help me out further pls :sweat_smile:

Edit: Never mind got it. Thanks for your help. Your site was great for visualizing :slight_smile:

Happy holidays :evergreen_tree: