Find the Longest Word in a String almost there!

Getting a type error that says length is undefined. Not sure where to go from here

Your code so far

  var longestWord = 1;
  var array = str.split(" ");
  for (var i = 0; i <= array.length; i++) {
    if (array[i].length > longestWord.length) {
      longestWord = array[i];
    else if (array[i].length <= longestWord.length) {
      longestWord = longestWord;
  return longestWord.length;

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36.

Link to the challenge:

Since longestWord is expected to hold a string, it should be initialized as the empty string.

var longestWord = "";

Numbers don’t have a length property, so you get the type error.

Then you have an off-by-one error in your for-loop. Check the condition carefully.

1 Like