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

269
Views
Why doesn't the second code work the same as the first code?

The First Code works correctly and displays the right answer which is 19.

function findLongestWordLength(str) {
  let high = 0;
  let word = str.split(" ");
  
  for(let i = 0; i < word.length; i++)
  {
   if (word[i].length > high)
      high = word[i].length;
  }
  console.log(high)
}

findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");

The second code below, only works until the word "super-long" and logs 10 as the final output, which is incorrect. I'm trying to figure out what goes wrong here. It works fine with other sentences,

FOR REFERENCE

The str.length in the sentence is 60(spaces included), and there are 9 spaces in between the entire sentence


function findLongestWordLength(str) {
  let high = 0;
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] != " ") {
      count++;
    } else {
      if (count >= high)
        high = count;
      count = 0;
    }
  }
  return high;
}
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

count could be holding a non-zero value at the end of the loop, which will get ignored. Just add a check at the end of the loop as well to update that value.

for(let i = 0; i < str.length; i++)
  {
    if (str[i] != " ") count++;
    else 
    {
      if(count >= high) high = count;
      count = 0;
    }
  }
if(count >= high) high = count;
about 4 years ago · Juan Pablo Isaza Report

0

In order to get 19, you have to end your string with a space. Because the last character of "otorhinolaryngology" is a 'y', you simply increment count at the very end and you never hit your else condition which will update high. Put a space at the end, add an extra condition checking if i == str.length -1 Or simply use the length algorithm, or, as I would prefer, use a reducer like so:

const findLongestWordLength = str => str.split(' ').reduce((acc, word) => word.length > acc ? word.length : acc, 0)
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!