Hey I’m getting larger results with this code than I should be. What am I missing or doing incorrectly? Tried adding [i] to return splitStr[i].length but doesn’t look quite right. Thanks
** update just realized using return splitStr[i].length insn’t working because it’s not storing a string globally trying to figure this out now
Your code so far
function findLongestWordLength(str) {
var splitStr = str.split(" "); //splitting the string into words
for (var i = 0; i < splitStr.length; i++) { //running through the loop to log length of each word
return splitStr.length; //need to return the largest length of a word in the string, but not sure how to store the largest word
}
}
console.log(findLongestWordLength("May the force be with you"));
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36.
As soon as your function hits the return statement in the first iteration of the for loop it returns the length of splitStr and the function ends. So your function will always return the length of splitStr and will never have a chance to find the longest word in the string.
What you want to do in that for loop is look at the length of the current word you are examining in the array. Is it the longest word you’ve encountered so far? Then you’ll want to save off its length. Basically, you keep track of the longest word length you’ve come across. After you’ve gone through the entire array you’ll have the longest length.
But here your are trying to use the push method, which is not valid for a number. What about assigning (=) the new length as the longest word length?
Also, I’d move all of those return keywords until below your loop. The very first time your code path hits a return, the loop will stop, so you need to hold off on the return until after your loop finishes.