# Find the longest word using recursion

Hey guys, could someone explain to me what’s happening in the recursive call in this function?

``````function findLongestWordLength(str) {
var words = str.split(" ");
/* BASE CALL*/
if (words.length === 1) {
return words[0].length;
}
/* RECURSIVE CALL*/
return Math.max(
words[0].length,
findLongestWordLength(words.slice(1).join(" ")) //Why don't we use .length here?
);
}

console.log(
findLongestWordLength("The quick brown fox jumped over the lazy dog")
);
``````

`findLongestWordLength` takes a string argument, so if you are going to call it recursively then you need to pass it a string. What does the above code return? Why would we need the `length` property here?

P.S. Using recursion to solve this problem is probably not the best method as it adds unneeded complexity to what is really a very simple solution.

1 Like

It’s probably better for you to pseudocode the function (i.e., writing the plain english sentence for each line of the function), e.g.:

``````function findLongestWordLength(str) {
var words = str.split(" ");  // convert the sentence into an array of words
if (words.length === 1) {  // ...
...
}
``````

Search in google or Mozilla Developer Network for any operation that you don’t know, e.g.: what is .join javascript? what is .split? .slice method javascript?
Reverse engineering is one of the best way to learn. If you can do this, next time you have a difficult problem, you can pseudocode first before diving into writing the function. Beside, pseudocoding a perfectly working function could help nail that understanding in our head more solid.

1 Like

Thank you sir. I was stuck with this for hours and now it makes sense! Yes, I agree. I was just looking at more complex solutions to these basic algorithm challenges here on freeCodeCamp, just to challenge myself you know.

That’s right sir, I try to do that as much as possible. It’s really helpful!

I already know the .slice() and .join() methods on JavaScript. I was just curious with the function code in the recursive call, as it was difficult to understand. @bbsmooth already said that the str argument has to be a string in order to execute the recursive call.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (`</>`) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

No problem. This is my first time asking for a solution here on the forum, I didn’t know I was supposed to do that.

``````//Like this
``````

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