Scope issue? -Basic Alg. Find Longest Word in String

Tell us what’s happening:
I’m really trying to solve this on my own without relying so heavily on hints and peeking at the solutions. As you can see, I’ve split the string up by word, and then attempted to make a loop that counts the letters in each word. I thought my loop worked because when I console.log count inside the loop, I got this:

Result of console.log(count) inside for loop:
3
5
5
3
6
4
3
4
3

Yay! I thought I was almost done. All I have to do now is figure out how to return the largest number. But nothing I did after was working, and I couldn’t figure out why until I tried to console.log count outside of the for loop:

Result of console.log count outside of for loop:

3 << Is it stopping after one loop? Why 3?

I’ve looked at tutorials about scoping and for loops, but can’t figure out where I’m going wrong. I changed “let” to “var” but that did nothing. I tried declaring var count outside of the function, but that did nothing.

Please help me understand where I’m going wrong. In the meantime, I’m going to review basic Javascript concepts.

Your code so far


function findLongestWordLength(str) {
//first split the string up by word and make array
let splitStr = str.split(" ")
//get a count of all the words in the array
var count;
for (var i = 0; i < splitStr.length; i++) {
count = splitStr[i].length;


}

console.log(count)


return str.length;
}

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/84.0.4147.105 Safari/537.36.

Challenge: Find the Longest Word in a String

Link to the challenge:

You are looking for the biggest. I think you want some sort of a check for ‘big’ in this line.

1 Like

Thank you for the hint Jeremy,

I ended up using an if statement, after finding the blog article that explains three ways to solve this :slight_smile:. I had the right idea, but I was intent on creating additional code to check for the biggest number outside of that for loop. I guess my thought process was…

“OK, step two is finished, so I’m done with the for loop, let’s do something else underneath the loop to find the biggest number.”

I better improve with practice. At this rate, it will take me months to get through the Basic Algorithm challenges.

Taking a short break before going on.