Finding the longest word in a string

Finding the longest word in a string
0

#1

Tell us what’s happening:
The code below works for all the test parameters except the last one, which is this -

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

Instead of returning 19, it returns 10. what seems to be the problem?
Your code so far


function findLongestWordLength(str) {
    let longest=1;
    let count=0
    for(let i=0;i<str.length;i++){
      if(str[i]!==" "){
        count++;
      }
      else{
        if(count>longest){
           longest=count;
        }
        count=0;
        continue;
      }
    }
    return longest;
  }
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 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


#2

You are only updating longest when you encounter a space. The last character in the string isn’t a space, so longest does not get assigned a new value at the end of the loop.

Also, your use of continue is pointless. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue for more.


#3

Thank you very much. It all makes sense now.