Find the Longest Word in the given String

Tell us what’s happening:
error: Cannot read property ‘length’ of undefined
I am not able to rectify the error please help
Constructive criticism appreciated

Your code so far


function findLongestWordLength(str) {
  let arr=str.split(" ");
 // console.log(arr);
  let n=arr.length;
  let longest=0;
  //console.log(arr[2].length);
  for(let i=0;i<=n;i++)
  {
    if(longest < arr[i].length)
     {
      longest = arr[i].length;
    }
  }
  return longest;
}

console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));

Your browser information:

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

You have a problem here in number of times you are iterating over loop.
For example:

var arr = ["a","b","c","d"]

Now, if i loop though this.

for(let i=0;i<=arr.length;i++){
  ... here we have i <= arr.length..
... length of our arr is 4...
...however arrays are zero-indexed...
....so when we are having i=0, we are already looping through the array when i=3. 
 }

Remember this and try solving.
Hope this helps.

thnks i will remeber it

1 Like

I edited your code
Here is how I passed the tests using what you used


function findLongestWordLength(str) {
  let arr=str.split(" ");
  console.log(arr);
  let longest=0;

  for(let i=0;i<arr.length;i++)
  {
    if(arr[i].length > longest)
     {
      longest = arr[i].length;
    }
  }

  return longest;

}


console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));