Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
Could someone please illustrate this recursive function?

I've read all the documentation on recursive functions and Math.max but I still don't quite understand how this function works. Can someone explain what's happening here step by step? In particular, the second return statement involving Math.max().

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(' '))
  );
}

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Why would someone write something so terrible!

Let's look at "hello goodbye all"

This code is saying:

  1. Break it up into words ['hello', 'goodbye', all']
  2. If there is only one word, it's length is the answer
  3. If there is more than one word, find the length of the first word.
  4. Put everything except the first word back into a string (WTF!?!) and recursively find the longest word in that.
  5. Take the maximum of those two values calculated in steps 3 and 4.

The idea of breaking the string into words, and then putting all the words except the first back into a string just so you can call yourself recursively is pretty bizarre.

So a typical run looks like:

findLongestWordLength('hello goodbye all')
    = max(5, findLongestWordLength('goodbye all'))
    = max(5, max(7, findLongestWordLength('all')))
    = max(5, max(7, 3))
    = max(5, 7)
    = 7

Note that this is the standard trick of recursion. You prove the code works by assuming that it works on everything that is shorter.

Obviously this code works on all strings with one word in it. And given a string with n > 1 words in it, you assume that you're going to get the right answer when you call it with a string with n - 1 words in it, and then use that to get the right answer for your current string.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!