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: