Help on Find the Longest Word in a String algorithm

Help on Find the Longest Word in a String algorithm
0.0 0

#1

I thought I solve this algorithm beautifully. lol However, my return statement gives me an error message. See my code and error message below. Can anyone tell me what I’m doing wrong? :slight_smile: Thank you.

“SyntaxError: Illegal return statement”

function findLongestWord(str) {
  var newArray = str.split(' ');
  var i = 0;
  var b = 0;
  
  while( i  <= newArray.length() )
 
      if( newArray[i].length >= b){
          b = newArray[i].length; 
      }
  
      i++;
    }
  
  return b;
}

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

#2

Your code has many errors. The first one you have encountered is because you did not put a { at the end of the while statement. The second error you will encounter once you add the missing {, is length is not a function, so it should not have () after it in the while loop condition. You have other errors, but I will see if you can figure those out on your own.


#3

Okay…I got too excited with my code without going over the easy stuff. I believe I corrected all of the major fixes. However, I do have a new error message. Which I guess is a good thing. Error messages does lead to learning something new. LOL

Type error: Cannot read property 'length' of undefined.

function findLongestWord(str) {

var newArray = str.split(’ ');
var i = 0;
var b = 0;

while( i <= newArray.length){

if( newArray[i].length > b){
b = newArray[i].length;
}

i++;
}

return b;
}

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

What does my error message really mean?


#4

Look very closely at the characters you are using inside the split( ). One of those is not a single quote.

Also, once you resolve this issue, you will need to take a hard look at the following line of code:

while( i <= newArray.length){

Remember, arrays are zero-indexed, so the length of the array is always going to be one more than the last index in the array. For example, if I have the following array:

var myArray = [ 2, 4, 6];

The length of the array is 3, but the last index is 2 (for the element of value 6). If I try to reference an index greater than 2, I will get undefined.


#5

I got it. Thank you again.