Find the longest word in a string help please

Find the longest word in a string help please
0

#1

Good morning fellow coders! Can someone please tell me what is wrong with my code? Or at least give me a hint? I keep getting “TypeError: Cannot read property ‘length’ of undefined. :confused: The following is my code:
function findLongestWord(str) {
var longestSoFar = 0;
str.split(” ");

for (var i = 0; i < str.length; i++) {
if (str[i].length > str[i + 1].length) {
longestSoFar = str[i].length;
}
else if (str[i].length < str[i + 1].length) {
longestSoFar = str[i + 1].length;
}
}

return longestSoFar;


#2

I’ll drop a few hints before I go to sleep (it’s already midnight here and I can’t stay awake any longer)

.split() returns a new array. It doesn’t modify str in-place (or any string function for that matter).

Check what you’re comparing against. For every word in the string, is this word longer than the current longest word?


#3

Awesome! Thank you so much!


#4

Here’s my solution :

function findLongestWord(str) {
var wordArr = str.split(" ");

var longestWord = 0;

for (var i = 0; i < wordArr.length; i++) {
if (wordArr[i].length > longestWord) {
longestWord = wordArr[i].length;
}
}
return longestWord;
}

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

However at first i was having problem in the “for loop”. my code was:

for (var i = 0; i <= wordArr.length; i++)

that equal sign was making all the difference. but I’m still not sure what was wrong with the equal sign! I think its something simple but i don’t get it. So, can someone please help me understand this.


#5

Let’s take an array of words wordArr = ['alfa', 'beta', 'charly'];

When you have

for (var i = 0; i <= wordArr.length; i++)

and the loop reaches the last element

i = wordArr.length

what will wordArr[i] be?


#6

ah! got it! thanks so much. it was simply - but i got confused !!! the equal sign was taking it to one extra mile!!! :slight_smile: