A problem with my loop

Tell us what’s happening:
Describe your issue in detail here.
How can I get my for of loop to loop through the entire array and just stop at the first instance since it is bigger than zero? Why does it stop at the first instance instead of checking the others to see if they are more than three?

  **Your code so far**

function findLongestWordLength(str) {
//You will need to loop through the words in the string.
//You will need to figure out a way to keep track globally of the greatest current length.
//Do you remember how to get the length of strings?
let newStr = str.split(' ')
for(let word of newStr){
  let longest = 0;
  if(longest < word.length){
    longest = word.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/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36

Challenge: Find the Longest Word in a String

Link to the challenge:

The keyword return will exit the current function, always. The function is over at that point.

You are almost there. You should think about where longest should be used, the scope of it. And think about where you want to return the value.

I was able to move a few things around and get it to work.

1 Like

I got it, I took longest variable, and the return statement out of the for of loop. Now it returns the longest word. Thank you!

2 Likes

Awesome. Make sure you understand why.

You’re right and I figured it out. The longest would return as 3 because that is bigger than zero so it would complete the return statement inside the for of loop. Now since longest is declared and returned globally the entire for of loop is iterated through and the real longest number is returned.

1 Like