Why bother slicing the string in this solution?

Was checking my solution to a lesson in the data structures section and looking at the other solutions to learn a bit and I stumbled upon this:

function findLongestWordLength(str) {

  // split the string into individual words

  const words = str.split(" ");

  // words only has 1 element left that is the longest element

  if (words.length == 1) {

    return words[0].length;

  }

  // if words has multiple elements, remove the first element

  // and recursively call the function

  return Math.max(

    words[0].length,

    findLongestWordLength(words.slice(1).join(" "))

  );

}

I am wondering why str is converted to an array then its elements turned back into strings in the recursive function.

Is the recursive function checking the length of the element in an array against the max value, then turning that element back into a string?

This solution I am barely grasping so far. If anyone can also just generally comment on what is happening I would really appreciate it.

Thanks.

Because the first thing the function does is using a string-method .split(), which would cause an error, if it wasn’t given a string.

Yeah recursions are generally kinda hard to grasp at first.
If you haven’t done the lesson on recursion, randomly explaining one you came along seems a bot much.

Generally though, you have to think of recursion like a stack of function calls. Like a stack of paper. Each time the function calls itself, it’s like adding a piece of paper with a side calculcation and putting it on the stack. First the stack grows until you reach a point where you no longer have recursive calls - then you solve the papers from top to bottom.

Thanks for the response. I did do the lesson on recursion, it is one of the only stumbling blocks that I have hit so far generally. I sort of grasp the stack element to them. I was conceptualizing them as loops but realized that is not correct.

In this example I am a little confused on how exactly that recursive function cycles through the string, there is no indicator that cycles through the indexes- to me the way I am seeing that line is that it is continually slicing index[0] off the array. But the slice method takes that element into another array and leaves the array it acts on intact… thus the function is continually calling the same variable sitting in the [0] index.

That is how I read that, but obviously it is not what is happening because the recursive function returns as expected.

I’d recommend looking into the documentation, if you are troubled :wink:
Because .slice() actually returns the array “starting with that index” → meaning .slice(1) creates a slice of the array starting with index 1 AND up to the end. Thus the new array it is giving to the recursion is the old array minus the [0] element. That’s how it goes through the array :wink:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.