Trying to understand recursion problem

Tell us what’s happening:
Hi I am trying to understand this coding problem. It uses recursion, and I am unsure how it works. It’s from a course I’m taking, and I want to understand what it’s doing. The specific part that is tripping me up is when Slice is called. It is called twice. I am confused what’s happening each time it is called. A step through each iteration would be really nice. Thanks in advance for explaining and helping me to understand it!

The coding challenge: Write a recursive function called capitalizeWords. Given an array of words, return a new array containing each word capitalized.

Example:

let words = ['thanks', 'for', 'helping'];
capitalizeWords(words);  // ['THANKS', 'FOR', 'HELPING']
function capitalizeWords (array) {
  if (array.length === 1) {
    return [array[0].toUpperCase()];
  }
  let res = capitalizeWords(array.slice(0, -1));
  res.push(array.slice(array.length-1)[0].toUpperCase());
  return res;
}

Welcome to forum!

I’ve edited your post for readibility purposes.

Here’s my opinionated feedback: this challenge will not teach you anything good, definitely not a recursion and you should just skip it.

Function of this function is to take array and format each item in a specific way. Recursive is such function that might need it’s own functionality while running, for example if some items of the given array themselves are arrays of items that also needed to be formatted, like this:

// Recursive array
['thanks', 'for', ['helping', 'to' ['understand', 'recursion']]]

There is no groud for recursion in your challenge and you practically have to hack it out of nothing. There are specific methods that are created specifically for the tasks like this, one of them is .map(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Implementing map using recursion is a very basic exercise, and essential to understanding tail recursion. FCC doesn’t exactly go about pedagogy in a very structured way (or even always coherent) but it’s certainly a valid exercise.