Longest Word in a String: why var longestWord=0;?

Tell us what’s happening:
hi can someone tell me why we the variable var longestWord=0; equals zero, what is the logic behind it?

Your code so far

function findLongestWord(str) {
  //Primero añadimos dentro del parentesis de .split(" ") comillas separadas con espacio para que queden las palabras divididas por comillas
var strSplit=str.split(" ");
//segundo: inicia una variable que contendrá la longitud del string mas largo.
var longestWord=0;
//creamos un for loop
for (var i =0; i< strSplit.length; i++){
if (strSplit[i].length>longestWord){
longestWord= strSplit[i].length;

}
  
}
  
  return longestWord;
}

findLongestWord("The quick brown fox jumped over the lazy dog");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/find-the-longest-word-in-a-string

That variable holds the longest length you’ve found so far. Since at that point you haven’t started looking at the words yet, you can say that you haven’t found anything yet, so you start at zero.

Suppose you gave it a different starting value, say 5. It will work well if the words have more than 5 characters. But what if the longest word in the array only has 4 characters? Since 4 is not greater than 5, it will not update the longestWord variable with the correct value.

1 Like