Find the Longest Word in a String (I pass all the tests except for a last...)

Tell us what’s happening:

Hey, I pass every test in this exercise except for the last one which is:

findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") should return 19.

Could somebody explain why my code doesnt pass the last test?

Your code so far


function findLongestWordLength(str) {
  var arr = [];
  var leng = [];
  var largest = 0;
  arr = str.split(" ");
  for (var i = 0; i < arr.length; i++) {
    leng.push(arr[i].length);    
  }

  for (var j = 0; j <= largest; j++) {
    if (leng[j] > largest) {
      largest = leng[j];
    }
  }

  console.log(typeof leng);
  console.log(leng);  
  console.log(largest); 
  

  return largest;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/

Your condition for when to stop looping in the last for loop is flawed (j <= largest), try using the length of one of the arrays for the condition instead.

1 Like

Thanks, i havent noticed it! Now it works :slight_smile: