Find the Longest Word in the given String

Find the Longest Word in the given String
0

#1

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/


#2

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.


#3

thnks i will remeber it


#4

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"));